When does the compiler generate a default constructor for you, and what does it leave the object with?
The compiler generates a default constructor for you only when the class declares no constructor at all. The generated one takes no arguments and its body does nothing except the implicit super call. Every field is therefore left at the type's zero value: null for references, zero for numbers, false for boolean, and the null character for char.
public class Main {
public static void main(String[] args) {
Settings s = new Settings();
System.out.println(s.name + "|" + s.retries + "|" + s.verbose);
Reader r = new Reader();
System.out.println(r.title + "|" + r.pages);
}
}
class Settings {
String name;
int retries;
boolean verbose;
}
class Reader {
final String title;
final int pages;
Reader() {
title = "untitled";
pages = 0;
}
}The output makes the consequence visible. The settings object prints null|0|false, which is legal but rarely what the designer intended. A name field that starts as null tends to produce a null pointer exception far from the constructor that caused it. The reader class avoids the problem by declaring its own constructor and setting sensible defaults, so the object is never null-named or ambiguous.
One subtlety: if any superclass lacks a no-argument constructor, the compiler-generated default constructor in the subclass is invalid, and you must write your own that calls the available super constructor explicitly.
The practical advice for an interview is to treat the implicit default constructor as a design smell in domain classes. If a class can only sensibly exist with certain values, require them in a constructor, and the compiler will then enforce that every caller supplies them.