为什么要打印而不是打印?

时间:2018-09-05 13:06:03

标签: java inheritance polymorphism

考虑一下:

class Animal {
    Animal(){
        System.out.println("Animal's constructor called");
        this.indentifyMyself();//??????????????
        System.out.println("Exit Animal's constructor");
    }
    void indentifyMyself(){
        System.out.println("I'm an Animal");
    }
}
class Human extends Animal{
    Human(){
        System.out.println("Human's constructor called");
        super.indentifyMyself();
        System.out.println("Exit Human's constructor");
    }
    @Override
    void indentifyMyself(){
        System.out.println("I'm Human");
    }
}
public class Main {

    public static void main(String[] args) {
        new Human();

    }
}

为什么打印?

动物的构造函数称为

我是人类(???我没想到这一点)

退出动物的构造函数

人类的构造函数称为

我是动物

退出人类的构造函数

不是:

动物的构造函数称为

我是动物

退出动物的构造函数

人类的构造函数称为

我是动物

如果任何人都可以对此行为进行详细说明,我将不胜感激。 请不要告诉我多余的答案,例如“是多态的Java行为”。 预先感谢

2 个答案:

答案 0 :(得分:2)

I'm Human

打印而不是预期的

I'm an Animal

因为实例的实际运行时类型是Human而不是Animal,所以从虚拟方法表中选择了覆盖的函数。

here所述,Java和C ++的行为在这方面有所不同。

答案 1 :(得分:0)

您已经覆盖了该方法,并且在运行时JVM执行了该方法的新版本。不是动物类的老版本