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

后端 未结 4 1843
北海茫月
北海茫月 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:03

    While over ridding or implementing the access level, we should go for same access level or wider to that access level.

    private < (default) < protected < public
    

    Public is wider most level.

    In Interface all members are default public. So, While implementing or over ridding we have to go for only public.

    0 讨论(0)
  • 2021-01-17 10:11

    Consider a class B which inherits from A. A.m() is public. Now consider this code:

    A obj = new B();
    obj.m();
    

    Should this call be allowed? Yes, it should, because obj is an object of type A! It is also an object of type B, but that is not necessarily known to the one using the object.

    Every object of type A must adhere to the contract (interface) for A. B extends A and must therefore also adhere to that contract.

    0 讨论(0)
  • 2021-01-17 10:12

    A subclass should always satisfy the contract of the superclass. See Liskov Substitution principle.

    The visibility of methods is part of this contract. So anything publicly visible in the superclass should be public in the subclass as well.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题