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

Tvrd picture Tvrd · Apr 2, 2013 · Viewed 7.2k times · Source

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() {
    }
}

Answer

Ian Roberts picture Ian Roberts · Apr 2, 2013

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.