Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private constructor usage in class

Tags:

java

If there is a private constructor, does the JVM insert a call to the super constructor?

I'm referring to the super() call in that private constructor.

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

class SubAlpha extends Alpha{
    private SubAlpha(){
        s+="sub";
    }
}

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

    public static void main(String[] args){
        new SubSubAlpha();
        System.out.print(s);   
    }
}

Here I don't get any compilation error. Here in the SubSubAlpha class there is private constructor. Is that compiler insert super() call in that if so, what happens in the SubAlpha class. Even there is private constructor. And if that is not accessed how the inheritance tree continues till the top.

like image 435
satheesh Avatar asked Mar 19 '11 07:03

satheesh


1 Answers

If there is private constructor does the JVM inserts call to super constructor?

Yes

The super constructor will always be called. (You can't instantiate an class, without also instantiating the super class at the same time.)

If you don't do it explicitly yourself, there will be an implicit call inserted for you, no matter if the constructor is private or public.


To be picky: It's actually not the JVM that inserts it, but the Java compiler:

public class Test {
    private Test() {
    }
}

is compiled into

private Test();
  Code:
   Stack=1, Locals=1, Args_size=1
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return
like image 109
aioobe Avatar answered Oct 06 '22 09:10

aioobe