我们可以在 Java 中覆盖受保护的方法吗?

javaobject oriented programmingprogramming更新于 2025/6/30 15:08:17

可以,超类的受保护方法可以被子类覆盖。如果超类方法受保护,则子类覆盖的方法可以具有protected或public(但不能具有default或private),这意味着子类覆盖的方法不能具有较弱的访问说明符。

示例

class A {
   protected void protectedMethod() {
      System.out.println("superclass protected method");
   }
}
class B extends A {
   protected void protectedMethod() {
      System.out.println("subclass protected method");
   }
}
public class Test {
   public static void main(String args[]) {
      B b = new B();
      b.protectedMethod();
   }
}

输出

subclass protected method

相关文章


有用资源