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?
问题:
回答1:
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:
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.
回答2:
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.
回答3:
The visibility only affects external accessibility. Being a public
method any external class can call it.
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.