我尝试了以下代码
public class HelloWorld {
public void printData(Test t) {
System.out.println("Reached 1");
}
public void printData(newTest t) {
System.out.println("Reached 2");
}
public void printData(newTest1 t) {
System.out.println("Reached 3");
}
public static void main(String args[]) {
Test t1 = new Test();
HelloWorld h = new HelloWorld();
h.printData(t1);
NewTest t2 = new NewTest();
h.printData(t2);
NewTest1 t3 = new NewTest1();
h.printData(t3);
Test t4 = new NewTest();
h.printData(t4);
Test t5 = new NewTest1();
h.printData(t5);
}
}
我有简单的课程
class Test {
}
class NewTest extends Test {
}
class NewTest1 extends Test {
}
我得到的输出是
Reached 1
Reached 2
Reached 3
Reached 1
Reached 1
从输出看,当 jvm 决定执行哪个函数时,它只考虑了引用的类型,而不考虑对象的实际类型。
为什么会这样?为什么 jvm 不能考虑实际对象的类型而不是指向它的引用的类型?