Dynamic method dispatching in Java(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
的内存位置,所以如果我调用该方法指向 C
的 A
引用,并且参数作为 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.
这篇关于Java中的动态方法调度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java中的动态方法调度


基础教程推荐
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- Java Swing计时器未清除 2022-01-01