gpt4 book ai didi

java - 为什么我可以用公共(public)方法覆盖 protected 方法?

转载 作者:IT老高 更新时间:2023-10-28 20:51:32 35 4
gpt4 key购买 nike

当我用 public 方法覆盖 protected 方法时,Java 编译器不会报错。这里到底发生了什么?由于父方法的可见性较低,是覆盖还是隐藏了父方法?

最佳答案

子类总是可以扩展访问修饰符,因为它仍然是父类(super class)的有效替代。来自 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)方法覆盖 protected 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23081671/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com