为什么这段代码不调用子类?Java中的继承

Rag*_*hav 4 java inheritance

public class Parent {
    public  void printParent()
    {
        System.out.println("I am the Parent");
        System.out.println("----this is ::---" + this);
         this.printChild();
    }
    private void printChild()
    {
        System.out.println("This is my child");
    }
}

public class Child extends Parent {
    private void printChild()
    {
        System.out.println("I am the child");
    }
}

public class RelationshipTester {
    @Test
    public  void testRelation()
    {
        Child parent = new Child();
        parent.printParent();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是输出: -

我是家长

----这是:: --- datastructures.lists.inheritance.Child@1a692dec

这是我的孩子

该对象属于Child类型,但它不调用子方法和父方法.我给了this.printChild();

Ste*_*n C 5

Parent类中,您已声明printChild为私有...并调用它.无法覆盖私有方法.您printChildChild类是不知道的Parent类.

如果您要将修改private器更改为public,那么您有一个覆盖,并且您的示例应该输出您期望的内容.


为什么Java不允许您覆盖私有方法?好吧,基本上,如果你能做到那么就没有办法写一个带有子类无法破解的抽象边界的类.这将(IMO)成为一个主要的语言设计短缺.

为什么Java报告错误或警告?那么没有错误,因为根据JLS,这是合法的Java.至于警告......如果你单独编译Parent就没有问题,因为编写的代码是声明并使用私有方法.如果单独编译Child,则编译器无法在Parent类中看到私有方法.(实际上,它甚至可能不存在于Parent你正在编译的.class文件的版本中.)只有你编译Parent并且Child同时编译器可能发现有点奇怪的东西.