[英]Why can I override a protected method with public method?
The Java compiler doesn't complain when I override a protected
method with a public
method.当我用
public
方法覆盖protected
方法时,Java 编译器不会抱怨。 What's really happening here?这里到底发生了什么? Is it overriding or hiding the parent method since the parent method has lower visibility?
由于父方法的可见性较低,它是覆盖还是隐藏父方法?
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:
覆盖或隐藏方法的访问修饰符(第 6.6 节)必须提供至少与覆盖或隐藏方法一样多的访问,如下所示:
- 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.
否则,会发生编译时错误。
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.另一方面,降低可见性是不允许的,因为外部类总是可以使用超类类型的引用来引用子类的对象并调用相同的方法。
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
来访问原始方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.