Constructor execution flow in Java - Time & Space Complexity
We want to understand how the time taken by constructors grows as we create more objects or use inheritance.
How does the constructor's work change when the program runs?
Analyze the time complexity of the following code snippet.
class Parent {
Parent() {
System.out.println("Parent constructor");
}
}
class Child extends Parent {
Child() {
super();
System.out.println("Child constructor");
}
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
}
}
This code creates a Child object, which calls the Parent constructor first, then its own.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Constructor calls during object creation.
- How many times: Each constructor runs once per object creation; Parent constructor runs before Child constructor.
Each time we create a new Child object, both Parent and Child constructors run once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 constructor calls (10 Parent + 10 Child) |
| 100 | 200 constructor calls (100 Parent + 100 Child) |
| 1000 | 2000 constructor calls (1000 Parent + 1000 Child) |
Pattern observation: The total constructor calls grow linearly with the number of objects created.
Time Complexity: O(n)
This means the time to create n objects grows directly in proportion to n.
[X] Wrong: "The Parent constructor runs multiple times per object creation."
[OK] Correct: Each object creation calls the Parent constructor exactly once before the Child constructor.
Understanding constructor execution flow helps you explain object creation and inheritance clearly, a useful skill in many coding discussions.
"What if the Child constructor called another method that creates multiple objects? How would the time complexity change?"