Constructor overloading in Java - Time & Space Complexity
Let's see how the time it takes to create objects changes when we have multiple constructors.
We want to know how the number of constructors affects the work done when making an object.
Analyze the time complexity of the following code snippet.
public class Box {
int width, height, depth;
public Box() {
width = height = depth = 0;
}
public Box(int w, int h, int d) {
width = w;
height = h;
depth = d;
}
}
This code shows two constructors for the Box class: one with no inputs and one with three inputs.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Assigning values to the object's fields inside the constructor.
- How many times: Each constructor runs once when an object is created; no loops or repeated steps inside.
Creating an object runs a fixed number of steps depending on the constructor used.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 3 assignments |
| 10 | Each object creation does 3 assignments, repeated 10 times |
| 100 | Each object creation does 3 assignments, repeated 100 times |
Pattern observation: The work per object is constant; total work grows linearly with how many objects you create.
Time Complexity: O(1)
This means creating one object with any constructor takes a fixed amount of time, no matter what.
[X] Wrong: "More constructors mean creating an object takes longer time."
[OK] Correct: Only the chosen constructor runs when creating an object, so the number of constructors does not affect the time for one object.
Understanding constructor overloading helps you explain how object creation works efficiently, a useful skill in many coding tasks.
"What if a constructor called another constructor inside it? How would the time complexity change?"