Java > Object-Oriented Programming (OOP) > Inheritance > Constructor Chaining
Constructor Chaining in a Multi-Level Inheritance Hierarchy
This example shows how constructor chaining works across multiple levels of inheritance, ensuring that the constructors of all superclasses are invoked in the correct order.
Code Snippet
In this example, `Grandparent` is the base class, `Parent` inherits from `Grandparent`, and `Child` inherits from `Parent`. When a `Child` object is created, the constructors are invoked in the order of inheritance: `Grandparent`, `Parent`, and then `Child`. Because none of the constructors explicitly call `super()`, the default no-argument constructor of each superclass is implicitly called.
class Grandparent {
public Grandparent() {
System.out.println("Grandparent constructor called");
}
}
class Parent extends Grandparent {
public Parent() {
System.out.println("Parent constructor called");
}
}
class Child extends Parent {
public Child() {
System.out.println("Child constructor called");
}
public static void main(String[] args) {
Child child = new Child();
}
}
Concepts Behind the Snippet
Real-Life Use Case
Consider GUI components. You might have a base `Component` class, a `Container` class that extends `Component`, and a `Button` class that extends `Container`. The constructor of `Button` would implicitly or explicitly chain to the constructors of `Container` and `Component` to initialize the basic properties and behavior of each class.
Best Practices
Interview Tip
Understanding how constructors are invoked in a multi-level inheritance hierarchy is a common interview topic. Be able to explain the order of execution and the role of `super()`.
When to Use Multi-Level Constructor Chaining
Use this when you have a complex class hierarchy where each class needs to initialize its own specific state and also relies on the initialization provided by its superclasses.
Memory Footprint
Similar to the previous example, the memory footprint is primarily determined by the object's fields, not the constructor chaining itself. However, proper constructor chaining can ensure that all required fields are initialized correctly, preventing potential issues later on.
Alternatives
The main alternative to constructor chaining would be to directly initialize variables from the superclasses within the subclass constructor. However, this is not recommended as it would duplicate code and make the code harder to maintain.
Pros
Cons
FAQ
-
In a multi-level inheritance hierarchy, which constructor is called first?
The constructor of the topmost superclass (the root of the inheritance tree) is called first. The constructors are then called down the hierarchy towards the subclass. -
If a class doesn't have a default constructor, what happens?
If a class doesn't have a default constructor and its subclass doesn't explicitly call `super()` with the correct parameters, a compile-time error will occur.