0
0
Javaprogramming~5 mins

Method overriding rules in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method overriding rules
O(1)
Understanding Time Complexity

We want to understand how the time it takes to run code changes when using method overriding in Java.

Specifically, how does calling an overridden method affect the program's running time as input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Parent {
    void display() {
        System.out.println("Parent display");
    }
}

class Child extends Parent {
    @Override
    void display() {
        System.out.println("Child display");
    }
}

public class Test {
    public static void main(String[] args) {
        Parent obj = new Child();
        obj.display();
    }
}
    

This code shows a child class overriding a method from its parent, then calling it through a parent reference.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Single method call to an overridden method.
  • How many times: Exactly once in this example.
How Execution Grows With Input

Since the method call happens once, the time does not grow with input size.

Input Size (n)Approx. Operations
101 method call
1001 method call
10001 method call

Pattern observation: The time stays the same no matter how big the input is.

Final Time Complexity

Time Complexity: O(1)

This means the time to call an overridden method stays constant regardless of input size.

Common Mistake

[X] Wrong: "Overriding a method makes the program slower as input grows because it adds extra steps."

[OK] Correct: Calling an overridden method is just one step and does not repeat or grow with input size, so it does not slow down the program as input grows.

Interview Connect

Understanding that method overriding does not add hidden time costs helps you explain how Java handles dynamic method calls efficiently.

Self-Check

"What if the overridden method contained a loop that runs n times? How would the time complexity change?"