0
0
Javaprogramming~5 mins

Why inheritance is used in Java - Performance Analysis

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

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?

Scenario Under Consideration

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

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

Calling a method through inheritance does not add extra steps per call.

Input Size (n)Approx. Operations
1010 method calls
100100 method calls
10001000 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.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with the number of method calls, inheritance does not add extra cost per call.

Common Mistake

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

Interview Connect

Understanding how inheritance affects performance helps you explain design choices clearly and shows you know how code structure impacts running time.

Self-Check

"What if we added many levels of inheritance? How would the time complexity of method calls change?"