Inheritance limitations in Java - Time & Space Complexity
We want to understand how the limits of inheritance affect the time it takes for a program to run.
Specifically, how does using inheritance or its restrictions change the work done by the program?
Analyze the time complexity of the following code snippet.
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
This code shows a simple inheritance where a Dog class overrides a method from Animal.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
sound()method once. - How many times: Exactly one time in this example.
Since there is no loop or recursion, the work stays the same no matter how many classes or objects exist.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 method call |
| 100 | 1 method call |
| 1000 | 1 method call |
Pattern observation: The execution time does not grow with input size here.
Time Complexity: O(1)
This means the program runs in constant time regardless of inheritance depth or number of classes.
[X] Wrong: "More inheritance levels always make the program slower."
[OK] Correct: Method calls in inheritance are resolved quickly by the JVM, so adding levels does not slow down the program noticeably.
Understanding how inheritance affects performance helps you explain design choices clearly and shows you know how code structure impacts running time.
"What if the method sound() called itself recursively? How would the time complexity change?"