It's easy to confuse the concepts of "default constructor" and "no-argument constructor" in Java. The reason is that a default constructor is a particular kind of no-argument constructor. However, not all no-argument constructors are default constructors.
If any constructor appears in the source code of a class, even an empty no-argument constructor, a default constructor is not generated and does not exist. Because Test
declares a constructor, it does not have a default constructor, so Test cFrame = new Test();
does not call a default constructor.
These two classes are identical in terms of behavior (both have a no-argument constructor that does nothing), but one has a default constructor and the other does not.
class NoDefaultConstructor {
NoDefaultConstructor() {
// This is a no-argument constructor with an empty body, but is not a default constructor.
}
}
class HasDefaultConstructor {
// This class has no declared constructors, so the compiler inserts a default constructor.
}
In each case, you can create an instance with new NoDefaultConstructor()
or new HasDefaultConstructor()
, because both classes have no-argument constructors, but only HasDefaultConstructor
's no-argument constructor is a default constructor.
Style note: If a constructor doesn't explicitly chain to another constructor with a call to super(...)
or this(...)
, a call to super()
is automatically inserted at the beginning of the constructor. You never need to write super()
in a Java constructor. Doing so adds visual noise and is unnecessary.