给定以下类别:
public class Super {
protected int x = 1;
public Super() {
System.out.print("Super");
}
}
public class Duper extends Super {
protected int y = 2;
public Duper() {
System.out.println(" duper");
}
public class Fly extends Super {
private int z, y;
public Fly() {
this(0);
}
public Fly(int n) {
z = x + y + n;
System.out.println(" fly times " + z);
}
public static void main(String[] args) {
Duper d = new Duper();
int delta = 1;
Fly f = new Fly(delta);
}
}
运行
Fly
时显示什么?我的想法是,由于它创建了Duper对象,因此将打印出
duper
。然后,它使用int参数转到Fly构造函数。 x是Super的1,y是Duper的2,n是Fly的1,所以1 + 2 + 1 = 4,所以我认为它也会打印fly times 4
。但是实际上Super duper
Super fly times 2
如果有人可以解释,那将是很好!
最佳答案
Duper d = new Duper();
实例化一个新的
Duper
,Duper()
构造函数隐式调用Super()
构造函数->打印“超级”(不返回行)
->然后显示“ duper”(带有换行符)
int delta = 1;
Fly f = new Fly(delta);
Fly
构造函数隐式调用Super()
构造函数->打印“超级”(无行返回)然后调用
this(0)
。编辑:在
Fly
中,private int z, y;
将z
和y
都初始化为0
(这是int
的默认值)然后,从
x = 1
继承Super
,因此将x
的值设置为1
,y
和z
的值仍为0
。构造函数
n
在调用1
时将public Fly(int n)
设置为new Fly(delta)
(增量为1
)并计算
z = x + y + n
x is initialised to 1 in Super
y is initialised to 0 by default in Fly
n is initialised to 1 from the constructor parameter
z = 1 + 0 + 1
z = 2
然后打印“飞行时间2”(带有换行符)