0
0
Javaprogramming~5 mins

Parent and child classes in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Parent and child classes
O(n)
Understanding Time Complexity

When working with parent and child classes, it's important to understand how the program runs as the input grows.

We want to know how the time needed changes when we create or use many objects from these classes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Parent {
    void greet() {
        System.out.println("Hello from Parent");
    }
}

class Child extends Parent {
    void greet() {
        System.out.println("Hello from Child");
    }
}

public class Main {
    public static void main(String[] args) {
        Parent[] arr = new Parent[1000];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new Child();
            arr[i].greet();
        }
    }
}
    

This code creates an array of child objects and calls a method on each one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that creates and calls greet() on each object.
  • How many times: It runs once for each element in the array, so 1000 times in this example.
How Execution Grows With Input

Each time we add more objects, the loop runs more times, doing more work.

Input Size (n)Approx. Operations
1010 creations and 10 greet calls
100100 creations and 100 greet calls
10001000 creations and 1000 greet calls

Pattern observation: The work grows directly with the number of objects; doubling objects doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time needed grows in a straight line with the number of objects created and used.

Common Mistake

[X] Wrong: "Since greet() is overridden, it might take longer for each call as n grows."

[OK] Correct: Each greet() call takes the same small amount of time regardless of how many objects exist; the number of calls matters, not the override.

Interview Connect

Understanding how loops over objects affect time helps you explain program speed clearly and confidently.

Self-Check

"What if we added a nested loop inside the main loop that also iterates over the array? How would the time complexity change?"