Why is it not allowed to narrow down scope of a method while overriding

后端 未结 4 1847
北海茫月
北海茫月 2021-01-17 09:27

In Java, when I override a method the compiler flags off any attempt to narrow down the visibility as an error. For ex: I can\'t override a public method as protected, while

4条回答
  •  执笔经年
    2021-01-17 10:26

    Assume parent class and child class with overriding method with public access modifier.

    class Parent{
    
    public void m(){
    // method implementation
    }
    
    }
    class Child extends Parent{
    @Override
    public void m(){
    //child implementation
    }
    }
    

    assume there are some classes which are utilising this functionality like this

    Parent p = new Child();
    p.m(); // this access is fine, because JVM calls Overriding method at run time
    

    Now if we change the access of overriding method to anything less than public

    class Child extends Parent{
    @Override
    void m(){
    //Child implementation
    }
    }
    

    Now some of the classes which were able to use the functionality of method m() may not be able access the function.This is not a desired behaviour.

    Hence the rule is Overriding method should not decrease the scope of overridden method.

提交回复
热议问题