Constructor chaining in Java - Time & Space Complexity
Constructor chaining means one constructor calls another in the same class. We want to see how this affects the time it takes to create an object.
How does the number of constructor calls grow when chaining happens?
Analyze the time complexity of the following code snippet.
public class Box {
int width, height, depth;
public Box() {
this(1, 1, 1); // calls the 3-parameter constructor
}
public Box(int w, int h, int d) {
width = w;
height = h;
depth = d;
}
}
This code shows one constructor calling another to set default values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Constructor call chaining (one constructor calls another exactly once)
- How many times: Each constructor calls another only once, so the chain length is fixed and small.
Execution grows by the number of constructor calls in the chain, which is fixed here.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 (one object) | 2 constructor calls |
| 10 (ten objects) | 20 constructor calls |
| 100 (hundred objects) | 200 constructor calls |
Pattern observation: The number of constructor calls grows linearly with the number of objects created, but each object creation involves a fixed small chain of calls.
Time Complexity: O(n)
This means creating n objects with constructor chaining takes time proportional to n, since each object requires a fixed number of constructor calls.
[X] Wrong: "Constructor chaining makes object creation take much longer because it repeats many times."
[OK] Correct: The chain length is fixed and small, so it adds only a constant extra cost per object, not a growing cost.
Understanding constructor chaining helps you explain object creation clearly and shows you know how code structure affects performance in simple ways.
"What if the constructor chain was longer or recursive? How would the time complexity change?"