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

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

提交回复
热议问题