0
0
Javaprogramming~5 mins

Abstract classes in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Abstract classes
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code with abstract classes changes as the program grows.

Specifically, how does using abstract classes affect the number of steps the program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


abstract class Animal {
    abstract void sound();
}

class Dog extends Animal {
    void sound() { System.out.println("Bark"); }
}

class Cat extends Animal {
    void sound() { System.out.println("Meow"); }
}

public class Main {
    public static void main(String[] args) {
        Animal[] animals = {new Dog(), new Cat(), new Dog()};
        for (Animal a : animals) {
            a.sound();
        }
    }
}
    

This code creates an array of animals and calls their sound method using an abstract class reference.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array and calling the sound method on each animal.
  • How many times: Once for each animal in the array (n times, where n is the array length).
How Execution Grows With Input

Each animal in the array causes one call to sound(). As the number of animals grows, the total calls grow the same way.

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

Pattern observation: The number of operations 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: "Using abstract classes makes the program slower because of extra overhead."

[OK] Correct: The abstract class itself does not add extra loops or repeated work; it just helps organize code. The main time depends on how many times methods are called, not on abstraction.

Interview Connect

Understanding how abstract classes affect time helps you explain design choices clearly and shows you know how code structure relates to performance.

Self-Check

"What if we added a nested loop inside the sound method that runs m times? How would the time complexity change?"