问题
I tried the following code
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);
}
}
and I have simple classes
class Test {
}
class NewTest extends Test {
}
class NewTest1 extends Test {
}
and the output I got is
Reached 1
Reached 2
Reached 3
Reached 1
Reached 1
From the output it looks like when jvm decides which function to execute it takes into consideration only the type of reference and not the actual type of the object.
Why does this happen? Why can't jvm take into consideration the type of actual object rather than the type of the reference pointing to it?
回答1:
Function overloading is compile time polymorphism and here the compiler decide which version of the method will called.For the compiler it's very difficult to know the actual object for run time so it check the reference type only irrespective of the object it's going to point.
来源:https://stackoverflow.com/questions/18265994/behavior-of-method-overloading-in-java