0
0
Javaprogramming~5 mins

Partial abstraction in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Partial abstraction
O(n)
Understanding Time Complexity

We want to understand how the time needed to run code with partial abstraction changes as input grows.

How does the use of abstract methods affect the number of steps the program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


abstract class Shape {
    abstract double area();
}

class Circle extends Shape {
    double radius;
    Circle(double r) { radius = r; }
    double area() { return Math.PI * radius * radius; }
}

// Using the area method on a list of shapes
for (Shape s : shapes) {
    double a = s.area();
}
    

This code calls an abstract method area() on each shape in a list, using partial abstraction.

Identify Repeating Operations

Look for loops or repeated calls that affect time.

  • Primary operation: Calling area() on each shape object.
  • How many times: Once per shape in the list, so as many times as the list size.
How Execution Grows With Input

Each shape in the list requires one call to area(). As the list grows, calls grow the same way.

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

Pattern observation: The number of operations grows directly with the number of shapes.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with the number of shapes processed.

Common Mistake

[X] Wrong: "Using abstract methods makes the code slower by a lot because of extra overhead."

[OK] Correct: The overhead of calling an abstract method is very small and does not change the overall linear growth with input size.

Interview Connect

Understanding how abstraction affects time helps you explain design choices clearly and shows you know both code structure and performance.

Self-Check

What if the area() method itself contained a loop over a large data structure? How would the time complexity change?