给定以下类别:

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();


实例化一个新的DuperDuper()构造函数隐式调用Super()构造函数

->打印“超级”(不返回行)

->然后显示“ duper”(带有换行符)

int delta = 1;
Fly f = new Fly(delta);


Fly构造函数隐式调用Super()构造函数->打印“超级”(无行返回)
然后调用this(0)

编辑:在Fly中,private int z, y;zy都初始化为0(这是int的默认值)
然后,从x = 1继承Super,因此将x的值设置为1yz的值仍为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”(带有换行符)

09-30 23:34