java – 为什么可以用public方法覆盖受保护的方法?

当我用公共方法覆盖受保护的方法时,Java编译器不会抱怨.这里真的发生了什么?是否覆盖或隐藏父方法,因为父方法具有较低的可见性?
最佳答案
子类可以随时扩展访问修饰符,因为它仍然是超级类的有效替换.从Java规范约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.

转载注明原文:java – 为什么可以用public方法覆盖受保护的方法? - 代码日志