Why inheritance is used in Java - Performance Analysis
We want to understand how using inheritance affects the time it takes for a program to run.
Specifically, we ask: How does inheritance change the number of steps the program needs?
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 class Dog inheriting from Animal and overriding a method. It calls the method on a Dog object using an Animal reference.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the overridden method sound()
- How many times: Once in this example, but could be many times if called repeatedly
Calling a method through inheritance does not add extra steps per call.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls |
| 100 | 100 method calls |
| 1000 | 1000 method calls |
Pattern observation: The number of steps grows directly with how many times the method is called, inheritance itself does not slow it down.
Time Complexity: O(n)
This means the time grows linearly with the number of method calls, inheritance does not add extra cost per call.
[X] Wrong: "Inheritance makes method calls slower because it adds extra steps to find the method."
[OK] Correct: Modern Java uses efficient method lookup, so calling an overridden method through inheritance is just as fast as calling a normal method.
Understanding how inheritance affects performance helps you explain design choices clearly and shows you know how code structure impacts running time.
"What if we added many levels of inheritance? How would the time complexity of method calls change?"