Search code examples
javaclassconstructorinitializing

What gets called when you initialize a class without a constructor?


So when a class has a private constructor you can't initialize it, but when it doesn't have a constructor you can. So what is called when you initialize a class without a constructor?

As example, what is called here (new b())??

public class a {
    public static void main(String args[]) {
        b classB = new b();
    }
}

public class b {
    public void aMethod() {
    }
}

Solution

  • There's no such thing as a "class without a constructor" in Java - if there's no explicit constructor in the source code the compiler automatically adds a default one to the class file:

    public ClassName() {
      super();
    }
    

    This in turn can fail to compile if the superclass doesn't have a public or protected no-argument constructor itself.