使用超类引用调用重载的继承方法 [英] Calling overloaded inherited methods using super class reference
问题描述
我不明白这种Java行为。我有两个课程:
I do not understand this Java behavior. I have two classes:
class C1 {
public void m1(double num) {
System.out.println("Inside C1.m1(): " + num);
}
}
class C2 extends C1 {
public void m1(int num) {
System.out.println("Inside C2.m1(): " + num);
}
}
这是我的主要内容:
public class Main {
public static void main(String[] args) {
C1 c = new C2();
c.m1(10);
}
}
结果是:
Inside C1.m1(): 10.0
当我预料到:
Inside C2.m1(): 10
当我尝试完成代码语法时,我发现了这个:
Also when I try to complete the code syntax, I found this:
< img src =https://i.stack.imgur.com/np07x.pngalt =在此输入图像说明>
其他m1的位置在哪里C2类?
Where is the other m1 of C2 class?
我还检查了我的Main.class的字节码,我看到了这个:
I also check the bytecode of my Main.class and I saw this:
Compiled from "Main.java"
public class com.company.Main {
public com.company.Main();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: new #2 // class com/company/C2
3: dup
4: invokespecial #3 // Method com/company/C2."<init>":()V
7: astore_1
8: aload_1
9: ldc2_w #4 // double 10.0d
12: invokevirtual #6 // Method com/company/C1.m1:(D)V
15: return
}
字节码告诉我它会调用C1.m1(D)V(第12行)。
The bytecode tell me that it will invoke the C1.m1 (D)V (line 12).
为什么C1的方法?我试图理解这种行为。
Why the method of C1? I am trying to understand this behavior.
推荐答案
你的两个方法名为 m1
没有相同的签名;超类中的一个采用 double
,而子类中的那个采用 int
。这意味着编译器将根据变量的编译时类型选择要调用的方法签名,即 C1
,并将调用 m1 (双)
。由于在运行时类 C2
没有覆盖版本 m1(double)
,因此版本来自 C1
被调用。
Your two methods named m1
do not have the same signature; the one in the superclass takes a double
, and the one in the subclass takes an int
. This means that the compiler will select the method signature to call based on the compile-time type of your variable, which is C1
, and will call m1(double)
. Since at runtime the class C2
doesn't have an overriding version of m1(double)
, the version from C1
is invoked.
规则是方法签名是在编译时根据编译时类型;方法调用在运行时根据匹配的签名进行调度。
The rule is that method signatures are computed at compile time based on compile-time types; method calls are dispatched at runtime based on matching signatures.
这篇关于使用超类引用调用重载的继承方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!