开发者

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

Why does the compiler give an error message when you reduce the visibility o开发者_如何学JAVAf a method while overriding it in the subclass?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜