Abstract classes in Java - Time & Space 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?
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 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).
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 |
|---|---|
| 10 | 10 calls to sound() |
| 100 | 100 calls to sound() |
| 1000 | 1000 calls to sound() |
Pattern observation: The number of operations 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: "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.
Understanding how abstract classes affect time helps you explain design choices clearly and shows you know how code structure relates to performance.
"What if we added a nested loop inside the sound method that runs m times? How would the time complexity change?"