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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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:
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.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.