【发布时间】:2019-01-19 01:15:46
【问题描述】:
我正在练习一个测试,我遇到了这个关于重载和静态和动态绑定的练习。询问以下代码的输出:
class Moe {
public void print(Moe p) {
System.out.println("Moe 1");
}
}
class Larry extends Moe {
public void print(Moe p) {
System.out.println("Larry 1");
}
public void print(Larry l) {
System.out.println("Larry 2");
}
}
class Curly extends Larry {
public void print(Moe p) {
System.out.println("Curly 1");
}
public void print(Larry l) {
System.out.println("Curly 2");
}
public void print(Curly b) {
System.out.println("Curly 3");
}
}
class Overloading {
public static void main (String [] args) {
Larry stooge1 = new Curly();
Moe stooge2 = new Larry();
Moe stooge3 = new Curly();
Curly stooge4 = new Curly();
Larry stooge5 = new Larry();
stooge1.print(new Moe());
stooge1.print(new Curly());
stooge1.print(new Larry());
stooge2.print(new Curly());
stooge3.print(new Curly());
stooge3.print(new Larry());
stooge5.print(new Curly());
}
}
我认为我得到了第一个,但在其他的我完全迷失了。这就是我解决第一个问题的方法:
在运行时stooge1 的类型是Curly,所以我们调用Curly 的print 方法。因为我们将Moe 类型的对象传递给打印,所以在Curly 中运行参数类型为Moe 的相应打印方法。这个方法的输出是Curly 1,正确答案。
但是,当我将这种技术应用于以下行时,我最终得到了错误的答案。有人能解释一下这个概念在 Java 中是如何工作的吗?
代码的正确输出是:
Curly 1
Curly 2
Curly 2
Larry 1
Curly 1
Curly 1
Larry 2
【问题讨论】:
-
您使用 Moe、Larry 和 Curly 而不是 A、B 和 C 的事实令人难以置信。
-
说
Larry extends Moe你说的是Larry is a type of Moe。 我完全迷失了 - 我也是。
标签: java