0
0
Javaprogramming~5 mins

Constructor execution flow in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Constructor execution flow
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time we create a new Child object, both Parent and Child constructors run once.

Input Size (n)Approx. Operations
1020 constructor calls (10 Parent + 10 Child)
100200 constructor calls (100 Parent + 100 Child)
10002000 constructor calls (1000 Parent + 1000 Child)

Pattern observation: The total constructor calls grow linearly with the number of objects created.

Final Time Complexity

Time Complexity: O(n)

This means the time to create n objects grows directly in proportion to n.

Common Mistake

[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.

Interview Connect

Understanding constructor execution flow helps you explain object creation and inheritance clearly, a useful skill in many coding discussions.

Self-Check

"What if the Child constructor called another method that creates multiple objects? How would the time complexity change?"