Why can't you reduce the visibility of a method in a Java subclass?

喜你入骨 提交于 2019-11-26 06:45:01

问题


Why does the compiler give an error message when you reduce the visibility of a method while overriding it in the subclass?


回答1:


Because every instance of the subclass still needs to be a valid instance of the base class (see Liskov substitution principle).

If the subclass suddenly has lost one property of the base class (namely a public method for example) then it would no longer be a valid substitute for the base class.




回答2:


Because if this was allowed, the following situation would be possible:

Class Sub inherits from class Parent. Parent has a public method foo, Sub makes that method private. Now the following code would compile fine, because the declared type of bar is Parent:

Parent bar = new Sub();
bar.foo();

However it is not clear how this should behave. One possibility would be to let it cause a runtime error. Another would be to simply allow it, which would make it possible to call a private method from outside, by just casting to the parent class. Neither of those alternatives are acceptable, so it is not allowed.




回答3:


Because subtypes have to be usable as instances of their supertype.



来源:https://stackoverflow.com/questions/1600667/why-cant-you-reduce-the-visibility-of-a-method-in-a-java-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!