Java 为什么我可以用公共方法覆盖受保护的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23081671/
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
Why can I override a protected method with public method?
提问by Monstieur
The Java compiler doesn't complain when I override a protected
method with a public
method. What's really happening here? Is it overriding or hiding the parent method since the parent method has lower visibility?
当我protected
用一个public
方法覆盖一个方法时,Java 编译器不会抱怨。这里到底发生了什么?由于父方法的可见性较低,它是覆盖还是隐藏父方法?
采纳答案by Harmlezz
A sub-class can always widen the access modifier, because it is still a valid substitution for the super-class. From the Java specification about Requirements in Overriding and Hiding:
子类总是可以加宽访问修饰符,因为它仍然是超类的有效替代。从 Java 规范中关于Overriding 和 Hiding 中的要求:
The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:
- If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
- If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
- If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.
覆盖或隐藏方法的访问修饰符(第 6.6 节)必须提供至少与覆盖或隐藏方法一样多的访问,如下所示:
- 如果被覆盖或隐藏的方法是公共的,那么覆盖或隐藏的方法必须是公共的;否则,会发生编译时错误。
- 如果被覆盖或隐藏的方法受保护,则覆盖或隐藏的方法必须是受保护或公开的;否则,会发生编译时错误。
- 如果被覆盖或隐藏的方法具有默认(包)访问权限,则覆盖或隐藏的方法不能是私有的;否则,会发生编译时错误。
回答by Rohan
From the point of view of an external class, the public method is just a new method, not an overriding method, since the external class could not access the protected method anyway.
从外部类的角度来看,公共方法只是一个新方法,而不是覆盖方法,因为外部类无论如何都无法访问受保护的方法。
On the other hand, lowering the visibility is not allowed because the external class can always use a reference of the type of a super-class to reference an object of the sub-class and call the same method.
另一方面,降低可见性是不允许的,因为外部类总是可以使用超类类型的引用来引用子类的对象并调用相同的方法。
回答by Mikael Lindl?f
The visibility only affects external accessibility. Being a public
method any external class can call it.
可见性仅影响外部可访问性。作为public
任何外部类都可以调用的方法。
Access level of the overriding method doesn't affect visibility of the original method. After override, with any access levels, the original method can only be accessed by calling super
in the subclass.
覆盖方法的访问级别不会影响原始方法的可见性。覆盖后,任何访问级别,原始方法只能通过super
在子类中调用来访问。