0
0
Javaprogramming~5 mins

Abstract vs concrete classes in Java - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Abstract vs concrete classes
O(1)
Understanding Time Complexity

Let's explore how using abstract and concrete classes affects the time it takes for a program to run.

We want to see how the program's steps grow when we use these classes.

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");
    }
}

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

This code defines an abstract class and a concrete subclass, then calls a method through the abstract reference.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the sound() method once.
  • How many times: Exactly one time in this example.
How Execution Grows With Input

Since the method call happens once, the time does not grow with input size.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays the same no matter how many objects or calls you might have in a bigger program.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time regardless of input size when calling methods on abstract or concrete classes.

Common Mistake

[X] Wrong: "Using abstract classes makes the program slower because of extra steps."

[OK] Correct: Calling methods through abstract classes uses normal method calls and does not add noticeable time compared to concrete classes.

Interview Connect

Understanding how abstract and concrete classes affect performance helps you write clean code without worrying about slowdowns.

Self-Check

"What if we added a loop that calls sound() on a list of 1000 animals? How would the time complexity change?"