What is constructor chaining in Java and are constructors inherited?
Constructors are not inherited. Every constructor starts by calling another one, either this(...) in the same class or super(...) in the parent, and Java inserts super() automatically if you write neither.
Explain it simply
To build a house you must first lay the foundation, and only then the floors. A child object works the same way: the parent part of the object is built first, then the child part. Constructor chaining is that order being enforced.
Example
class Person {
Person() { System.out.println("Person()"); }
}
class Student extends Person {
Student() {
this("unknown"); // chain to another constructor
System.out.println("Student()");
}
Student(String name) {
super(); // implicit if omitted
System.out.println("Student(name)");
}
}
// new Student() prints:
// Person()
// Student(name)
// Student()What to say in the interview
"A constructor is not inherited, but a subclass constructor must call a parent constructor as its first statement, via super(...). If I write nothing, the compiler adds super() with no arguments. If the parent has no no-argument constructor, the child must call super(args) explicitly or compilation fails. this(...) chains within the same class, and a constructor can use either this(...) or super(...), not both."
Common mistakes
- Putting
super(...)after other statements. It must be first (in Java versions before the newest previews). - Defining only a parameterised parent constructor and wondering why the child fails to compile.