NoEmptyConstructor
Incorrect
A constructor must do something
Correct
A constructor's body can be empty
CorrectionHere is what's right.
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.
Language
Java
Concepts
Related Misconceptions
MustInitializeFieldInConstructor
Special caseConstructorAllocates
Special caseConstructorReturnsObject
Special caseOther Languages
Literature References
The following papers directly or indirectly provide qualitative or quantitative evidence related to this misconception.