为什么我可以用公共方法覆盖受保护的方法? [英] Why can I override a protected method with public method?
问题描述
当我用一个 public
方法覆盖一个 protected
方法时,Java 编译器不会报错.这里到底发生了什么?由于父方法的可见性较低,是覆盖还是隐藏父方法?
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?
推荐答案
子类总是可以加宽访问修饰符,因为它仍然是超类的有效替代.来自关于要求的Java规范覆盖和隐藏:
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:
覆盖或隐藏方法的访问修饰符(第 6.6 节)必须提供至少与覆盖或隐藏方法一样多的访问权限,如下所示:
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:
- 如果被覆盖或隐藏的方法是公共的,那么覆盖或隐藏的方法必须是公共的;否则,会发生编译时错误.
- 如果被覆盖或隐藏的方法是受保护的,那么被覆盖或隐藏的方法必须是受保护的或公开的;否则,会发生编译时错误.
- 如果覆盖或隐藏的方法具有默认(包)访问权限,则覆盖或隐藏的方法不能是私有的;否则,会发生编译时错误.
这篇关于为什么我可以用公共方法覆盖受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!