Partial abstraction in Java - Time & Space 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?
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.
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.
Each shape in the list requires one call to area(). As the list grows, calls grow the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to area() |
| 100 | 100 calls to area() |
| 1000 | 1000 calls to area() |
Pattern observation: The number of operations grows directly with the number of shapes.
Time Complexity: O(n)
This means the time grows linearly with the number of shapes processed.
[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.
Understanding how abstraction affects time helps you explain design choices clearly and shows you know both code structure and performance.
What if the area() method itself contained a loop over a large data structure? How would the time complexity change?