Why polymorphism is needed in Java - Performance Analysis
We want to understand how using polymorphism affects the time it takes for a program to run.
Specifically, does choosing polymorphism change how the program's work grows as input grows?
Analyze the time complexity of the following code snippet.
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() { System.out.println("Bark"); }
}
class Cat implements Animal {
public void sound() { System.out.println("Meow"); }
}
public class Farm {
public void makeSounds(Animal[] animals) {
for (Animal a : animals) {
a.sound();
}
}
}
This code uses polymorphism to call the correct sound method for each animal in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of animals and calling their sound method.
- How many times: Once for each animal in the array.
Each animal in the list causes one call to sound().
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to sound() |
| 100 | 100 calls to sound() |
| 1000 | 1000 calls to sound() |
Pattern observation: The work grows directly with the number of animals.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of animals.
[X] Wrong: "Polymorphism makes the program slower because it adds extra steps."
[OK] Correct: The extra step is very small and does not change how the total work grows with input size.
Understanding how polymorphism affects time helps you explain design choices clearly and confidently.
"What if we replaced the array with a linked list? How would the time complexity change?"