Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What gets called when you initialize a class without a constructor? [duplicate]

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() {
    }
}
like image 386
Tvrd Avatar asked Apr 02 '13 14:04

Tvrd


2 Answers

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.

like image 116
Ian Roberts Avatar answered Oct 11 '22 04:10

Ian Roberts


It's called the default constructor. It's automatically added when a class doesn't explicitly define any constructors.

Formal specification:

If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:
If the class being declared is the primordial class Object, then the default constructor has an empty body.
Otherwise, the default constructor takes no parameters and simply invokes the superclass constructor with no arguments.

like image 28
Perception Avatar answered Oct 11 '22 04:10

Perception