Why can I override a protected method with public method?

蹲街弑〆低调 提交于 2019-12-17 16:15:18

问题


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.



来源:https://stackoverflow.com/questions/23081671/why-can-i-override-a-protected-method-with-public-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!