代码:
class Super {
void print(Super a) {
System.out.print("Super");
}
}
class Base extends Super{
void print(Base a) {
System.out.print("Base");
}
}
class Derived extends Base{
void print(Derived a) {
System.out.print("Derived");
}
}
class Test {
public static void main(String args[]){
Super a1= new Super();
Super b1= new Base();
Base c1= new Derived();
a1.print(new Base());
b1.print(new Derived());
c1.print(new Derived());
}
}
输出:“SuperSuperBase”
它是如何工作的,请解释一下?我明白不可能给出简短的答案,但是......理解起来很难
答案 0 :(得分:1)
输出:“SuperSuperBase”
Super a1= new Super();
a1.print(new Base());
Super
类对象是w.r.t Super
创建的。 <{1}}类的print()
方法将被调用。
Super
此处 Super b1= new Base();
b1.print(new Derived());
是类型b1
类的引用。因此,Super
类的print()
方法将被调用。
Super
此处 Base c1= new Derived();
c1.print(new Derived());
是类型c1
类的引用。因此,Base
类的print()
方法将被调用。