Java Inheritance - What is printed when Fly (program) is run?

PM123 :

Given the following classes:

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

What is printed when Fly is run?

My thought was since it created a Duper object, it would print out duper. Then, it goes to the Fly constructor with the int parameter. x is 1 from Super, y is 2 from Duper, n is 1 from Fly, so 1+2+1 = 4, so I thought it would print fly times 4 as well. But it's actually

Super duper
Super fly times 2

If someone could explain that would be great!

Bentaye :
Duper d = new Duper();

Instantiates a new Duper, Duper() constructor implicitly calls Super() constructor

-> prints "Super" (no line return)

-> then prints "duper" (with line return)

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

Fly constructor implicitly calls Super() constructor -> prints "Super" (no line return) then calls this(0).

EDIT: In Fly, private int z, y; initialises both z and y to 0 (this is the default value for int) Then x = 1 is inherited from Super so the value of x is then set to 1, the value of y and z remains 0. And n is set to 1 by the constructor public Fly(int n) when calling new Fly(delta) (delta is 1)

and calculate

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

Then prints " fly times 2" (with line return)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117427&siteId=1