为什么我可以使用公共方法覆盖受保护的方法? [英] Why can I override a protected method with public method?

查看:107
本文介绍了为什么我可以使用公共方法覆盖受保护的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆