Using a private constructor in a class

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

I mean the call super()in this 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 am not getting any compilation error. Here in the class SubSubAlphathere is a private constructor. This compiler call inserts super(), if so, what happens in the class SubAlpha. There is even a private constructor. And if it's not available, how does the inheritance tree continue to the top.

+5
source share
5 answers

. super(), super this. . , no-args, .

, private, ... , .

+4

, JVM ?

. ( , -.)

, , , .


: JVM, , Java:

public class Test {
    private Test() {
    }
}

private Test();
  Code:
   Stack=1, Locals=1, Args_size=1
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return
+8

, , , , . , :

class SubSubAlpha extends Alpha {

:

class SubSubAlpha extends SubAlpha {

... .

( , , -.)

+4

Java Programmer SourceBook. , . Java.

//: Cartoon.java
// Constructor calls during inheritance

class Art {
  Art() {
    System.out.println("Art constructor");
  }
}

class Drawing extends Art {
  Drawing() {
    System.out.println("Drawing constructor");
  }
}

public class Cartoon extends Drawing {
  Cartoon() {
    System.out.println("Cartoon constructor");
  }
  public static void main(String[] args) {
    Cartoon x = new Cartoon();
  }
} ///:~ 

:



+1

Ya, u can use super () to use the function and attribute from the superclass. its the same with normal java

-1
source

All Articles