为什么不能降低 Java 子类中方法的可见性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1600667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:14:39  来源:igfitidea点击:

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

javapolymorphismoverridingsubclassing

提问by ria

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

为什么在子类中重写方法时降低了方法的可见性,编译器会给出错误消息?

回答by Joachim Sauer

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

因为子类的每个实例仍然需要是基类的有效实例(参见Liskov 替换原则)。

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.

如果子类突然失去了基类的一个属性(例如一个公共方法),那么它就不再是基类的有效替代品。

回答by sepp2k

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 baris Parent:

Sub 类继承自 Parent 类。Parent 有一个公共方法foo,Sub 将该方法设为私有。现在以下代码可以正常编译,因为声明的类型bar是 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.

然而,目前尚不清楚这应该如何表现。一种可能性是让它导致运行时错误。另一种方法是简单地允许它,这将使从外部调用私有方法成为可能,只需强制转换到父类即可。这两种替代方案都不可接受,因此是不允许的。

回答by z -

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

因为子类型必须可用作其超类型的实例。