Java中的动态方法分派 [英] Dynamic method dispatching in Java

查看:68
本文介绍了Java中的动态方法分派的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是有关我的疑问的代码段.

The following is the code snipplet regarding my doubt.

class A {
    void someMethod(A param) {
        System.out.println("A");
    }
}

class C extends A {
    void someMethod(C param) {
        System.out.println("C");
    }
}

class DMD {
    public static void main(String[] args) {
        A ac = new C();
        C c = new C();
        ac.someMethod(c);
    }
}

输出:

A

但是我将输出排除为

C

因为我已经为C分配了内存,并且A引用了C的内存位置,所以如果我在A引用上调用指向C的方法,并且参数作为C类型传递,那么我希望someMethod(C)方法应该执行.

Because I have allocated memory for C, and A is referring to C's memory location, so if I call the method on the A reference which is pointing to C, and the argument is passed as C type, then I expect the someMethod(C) method should execute.

有人可以给我这种行为的正确原因吗?

Can anyone please give me the proper reason for this behaviour?

提前谢谢.

推荐答案

采用不同参数类型(重载)的方法的方法调用在编译时实现. (这是你的情况)

Method invocations on methods taking distinct argument types (overloading) are realized at compile time. (And this is your case)

如果所有3个方法都接受类型A的参数-即存在方法 overriding ,则只有在A之间存在继承关系的情况下,多态才会起作用并触发C方法. C,即C扩展了A.

If all 3 methods accepted argument of type A - i.e. method overriding was present, only then polymorphism would come into play and would trigger the method of C provided there is a inheritance relationship between A and C i.e. C extends A.

这篇关于Java中的动态方法分派的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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