Java中的动态方法调度

2022-01-24 00:00:00 polymorphism 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 的内存位置,所以如果我调用该方法指向 CA 引用,并且参数作为 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 的参数 - 即方法 覆盖 存在,那么只有多态性才会发挥作用并触发 C 的方法,前提是存在A 和 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.

相关文章