java中方法重载的行为 [英] Behavior of method overloading in java

查看:108
本文介绍了java中方法重载的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下代码

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决定执行哪个函数时,它会考虑仅类型引用而不是对象的实际类型

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.

为什么会这样?为什么jvm不能考虑实际对象的类型而不是指向它的引用类型?

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?

推荐答案

功能重载是编译时多态,这里编译器决定调用哪个版本的方法。对于编译器来说,很难知道运行时的实际对象,所以它只检查引用类型而不管它指向的对象。

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.

这篇关于java中方法重载的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆