Search code examples
javaconstructorscjp

Creating new object with constructor


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

Solution

  • 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 "