NoEmptyConstructor

Misconception:

It is not ok for a class to have a constructor with an empty body.

Incorrect

A constructor must do something

Correct

A constructor's body can be empty

Correction
Here is what's right.

The following class is perfectly fine:

public class Demo {
  public Demo() {
  }
}

Also this class is fine:

public class Counter {
  private int count;
  public Counter() {
  }
}

What happens when executing an empty constructor?

Despite the above constructor of class Counter being empty, the Java virtual machine will perform several actions when this constructor executes:

  • The instance variables are set to their default values (like there as a count = 0;).
  • The constructor of the superclass is called (like there was a super();).

But doesn’t it have to return the object?

In Java constructors do not return anything. There is no return type, not even void. The only job of a constructor is to initialize the object. It doesn’t allocate the object, and it doesn’t return it.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.