Super keyword in Java - Time & Space Complexity
Let's explore how using the super keyword affects the time it takes for a program to run.
We want to see how calling a parent class method with super changes the work done 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 {
void display() {
super.display();
System.out.println("Child display");
}
}
public class Test {
public static void main(String[] args) {
Child c = new Child();
c.display();
}
}
This code calls a method in the child class that also calls the parent class method using super.
Look for repeated actions that take time.
- Primary operation: Calling
display()method once. - How many times: The method runs once, calling parent method once inside.
Since the method calls happen only once, the work stays the same no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 method calls |
| 100 | 2 method calls |
| 1000 | 2 method calls |
Pattern observation: The number of operations does not increase with input size.
Time Complexity: O(1)
This means the time taken stays constant no matter how big the input is.
[X] Wrong: "Using super makes the program slower as input grows."
[OK] Correct: Calling a parent method with super is just one extra step and does not repeat or grow with input size.
Understanding how super works helps you explain method calls clearly and shows you know how inheritance affects program flow.
"What if the display() method called super.display() inside a loop that runs n times? How would the time complexity change?"