Behavior of method overloading in java [duplicate]

徘徊边缘 提交于 2020-01-30 03:27:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!