When does Java provide a default constructor, and when does it not?
If you write no constructor at all, the compiler adds a public no-argument one. The moment you write any constructor yourself, the compiler stops adding it.
Explain it simply
Think of a shop that gives you a free plain carry bag if you bring nothing. If you bring your own bag, they do not hand you the plain one as well.
The free constructor takes no arguments, has the same access as the class, and calls the parent's no-argument constructor with super(). It only exists when the class has zero constructors written by you.
Example
class A { } // compiler adds A() {}
class B {
B(String x) { } // you wrote one; no automatic B()
}
new A(); // fine
new B("hi"); // fine
new B(); // compile error: constructor B in class B cannot be appliedA related trap: if a child class has no explicit constructor, the compiler adds one that calls super(). If the parent has only a parameterised constructor, the child fails to compile.
What to say in the interview
"The compiler generates a no-argument constructor only when the class declares none. As soon as I define any constructor, I must add the no-argument one myself if I still want it. This matters for frameworks and subclasses that expect it."
Common mistakes
- Assuming the default constructor always exists.
- Forgetting that a subclass constructor silently calls super() and needs a matching parent constructor.