问题:Java中private方法能重写吗?

下面是测试代码

Java中private方法能重写吗?
public class A {
    private void print() {
        System.out.println("A");
    }
    public static void main(String[] args) {
        A a = new B();
        a.print();
        B b = new B();
        b.print();
    }
}

class B extends A {
    public void print() {    
        System.out.println("B");
    }
}
Java中private方法能重写吗?

运行结果

A

B

分析

在Java中,所有的private方法默认是final的,即不可继承的。所以当B继承A时,A的private方法print()不被B继承。

而B中的public方法print()相当于B添加的一个方法,不属于重写。

相关文章:

  • 2021-06-28
  • 2021-12-15
  • 2022-12-23
  • 2021-05-23
  • 2022-01-30
猜你喜欢
  • 2021-11-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-31
  • 2022-01-19
相关资源
相似解决方案