Default Constructor in Java
Problem
When a class declares no constructor at all, Java automatically supplies a no-argument default constructor that creates the object with every field left at its type's default value — 0 for numbers, false for booleans, null for references.
Define a class with no constructor at all, create an object from it, and observe its fields' default values.
Java Program
class Point {
int x;
int y;
// No constructor declared — Java supplies a no-argument default automatically
}
public class DefaultConstructorDemo {
public static void main(String[] args) {
Point p = new Point();
System.out.println("x = " + p.x + ", y = " + p.y); // int fields default to 0
}
}Output
Core Logic
Leaving a class with no constructor of its own lets Java supply an implicit no-argument one, which does nothing more than leave every field at its default value.
- 1
class Point { int x; int y; }declares no constructor anywhere in its body. - 2Java notices this and automatically supplies an invisible no-argument constructor behind the scenes — this is the actual default constructor.
- 3
new Point()compiles and runs fine, calling that supplied constructor, even though nothing inPointmentions one. - 4Since the supplied constructor's body does nothing at all, both
xandykeepint's default value of0.
new Point() and printing its fields shows x = 0, y = 0 — values neither set by any code, but by int's own default.Key Point: The moment a class declares ANY constructor of its own — even a no-argument one that explicitly sets values — Java stops supplying the automatic default entirely; the two look similar but only one is the true compiler-supplied default.
Key Concepts
Approach 2: Explicit No-Arg Constructor
class Point {
int x;
int y;
Point() {
// Explicitly written, so Java no longer supplies its own default
x = 5;
y = 5;
}
}
public class ExplicitNoArgConstructor {
public static void main(String[] args) {
Point p = new Point();
System.out.println("x = " + p.x + ", y = " + p.y);
}
}
Output
Core Logic
Declaring a no-argument constructor explicitly, with its own body, replaces the compiler-supplied default entirely and can initialize fields to whatever values are wanted.
- 1
Point()is written out by hand here, with the exact same empty parameter list as the implicit default. - 2Unlike the compiler-supplied version, this constructor's body actually runs
x = 5;andy = 5;. - 3Because a constructor now exists in the source code, Java does not add its own default constructor on top of this one.
- 4
new Point()still compiles and runs identically from the caller's perspective — only the field values it produces differ.
new Point() produces x = 5, y = 5 instead of the implicit default's x = 0, y = 0.Key Point: This looks like the same 'default constructor' at a glance — same empty parameter list — but it's technically a programmer-written no-arg constructor, not the compiler-supplied default, which is why the field values differ.