Method overriding rules in Java - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Single method call to an overridden method.
- How many times: Exactly once in this example.
Since the method call happens once, the time does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 method call |
| 100 | 1 method call |
| 1000 | 1 method call |
Pattern observation: The time stays the same no matter how big the input is.
Time Complexity: O(1)
This means the time to call an overridden method stays constant regardless of input size.
[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.
Understanding that method overriding does not add hidden time costs helps you explain how Java handles dynamic method calls efficiently.
"What if the overridden method contained a loop that runs n times? How would the time complexity change?"