Frage

The following code, when compiled and run gives the output as "alpha subsub". SubSubAlpha(); constructor should add "subsub " to variable s and that should be the output.

How come the output is " alpha subsub"?

class Alpha {
    static String s = " ";

    protected Alpha() {
       s += "alpha "; 
    }
}

public class SubSubAlpha extends Alpha {
    private SubSubAlpha() { 
       s += "subsub "; 
    }

    public static void main(String[] args) {
        new SubSubAlpha();
        System.out.println(s);
        // This prints as " alpha subsub".
        //Shouldn't this one be printed as " subsub"
        //Who made the call to Alpha(); ?
    }
}
War es hilfreich?

Lösung

When there is an hierarchy of classes the constructor of the subclass, in this case SubSubAlpha, always calls (first) the constructor of the superclass, in this case Alpha.

So what happens is actually:

private SubSubAlpha() { 
    super();
    s += "subsub ";
}

Thus, this makes:

s += "alpha ";
s += "subsub ";

Making the string "alpha subsub "

Andere Tipps

This is because when you create the object, the constructor of parent is invoked and it goes upto the Object class. Your Alpha internally extends Object class. So first SubSubAlpha constructor is invoked which calls Alpha constructor which in turn calls Object constructor, and the execution flows from Object through Alpha and in the end SubSubAlpha

For Information
Constructor calling hierarchy is that constructor of parent is called and then constructor of child gets called. But if you call a method, it is searched in the child class. If not found in the child class, then that method is searched in the parent class.

Reference
Order of Constructor Call

When calling the contructor of a subclass the first instruction is a call to the super class contructor.

So when you create a SubSubAlpha object, the Alpha constructor adds alpha to s property and then SubSubAlpha constructro adds subsub

Let me just slightly rewrite your contructor, with no change in the resulting bytecode:

private SubSubAlpha() { super(); s += "subsub "; }

Now it should be immediately clear what gets executed and in what order.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top