我正在为测试做练习,并且遇到了有关重载以及静态和动态绑定的练习。询问以下代码的输出:
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要打印的类型的对象,因此在Moe中运行了具有参数类型的相应打印方法Curly。该方法的输出为Curly
1,正确答案。
但是,当我将这种技术应用于以下几行时,我得到的答案是错误的。有人可以解释一下这个概念在Java中的工作原理吗?
该代码的正确输出是:
Curly 1
Curly 2
Curly 2
Larry 1
Curly 1
Curly 1
Larry 2