class Test {
    public static void main(String[] args) {
        Animal a = new Dog();
        Dog d = new Dog();

        d.makeNoise();  // output "Sub"
        a.makeNoise();  // output "Sub"  then what is use of calling this. why not call d.makeNoise() only.

    }
}

abstract class Animal {
    public void makeNoise() {
        System.out.println("Super");
    }
}

class Dog extends Animal {
    @Override
    public void makeNoise() {
        System.out.println("Sub");
    }
}


我们在这个主题上进行了15分钟的讨论(我想15分钟太长了),我向采访者解释了如何在a.makeNoise();的帮助下实现动态多态性,但是她仍然说两者都给出了相同的输出。
a.makeNoise();输出“ Sub”,然后调用它是什么用途。为什么不只调用d.makeNoise()
我也去了接口,但是仍然问题是子类引用是否给出相同的输出,然后为什么要使用超类引用。


  采访者的问题是,a.makeNoise();有什么区别?为什么不仅在两者给出相同输出时才调用d.makeNoise();


可能的正确答案是什么?

最佳答案

Animal a = new Dog();    // this animal is a dog
Dog d = new Dog();       // this dog is a dog


狗是狗,但是您声明了它。

a.getClass()等于d.getClass()等于Dog.class

另一方面:

Animal a = new Animal(); // this animal is an animal
a.makeNoise();           // prints "Super"

10-08 09:00