0
0
Javaprogramming~5 mins

Why polymorphism is needed in Java - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why polymorphism is needed
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each animal in the list causes one call to sound().

Input Size (n)Approx. Operations
1010 calls to sound()
100100 calls to sound()
10001000 calls to sound()

Pattern observation: The work grows directly with the number of animals.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of animals.

Common Mistake

[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.

Interview Connect

Understanding how polymorphism affects time helps you explain design choices clearly and confidently.

Self-Check

"What if we replaced the array with a linked list? How would the time complexity change?"