Default methods in Java - Time & Space Complexity
We want to understand how the time it takes to run code with default methods changes as the input grows.
How does adding a default method affect the speed of running interface methods?
Analyze the time complexity of the following code snippet.
interface Calculator {
default int add(int a, int b) {
return a + b;
}
}
class SimpleCalculator implements Calculator {
public int add(int a, int b) {
return Calculator.super.add(a, b);
}
}
public class Main {
public static void main(String[] args) {
SimpleCalculator calc = new SimpleCalculator();
for (int i = 0; i < 1000; i++) {
System.out.println(calc.add(i, i));
}
}
}
This code uses a default method in an interface and calls it many times in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the default method
addinside the loop. - How many times: The loop runs 1000 times, so the method is called 1000 times.
Each time the loop runs, it calls the default method once. So the total work grows as the number of loop runs grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to the default method |
| 100 | 100 calls to the default method |
| 1000 | 1000 calls to the default method |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time to run the code grows in a straight line as the input size grows.
[X] Wrong: "Using default methods makes the code run slower because they add extra overhead."
[OK] Correct: Default methods are just like normal methods and calling them inside a loop grows time linearly, not slower or faster than usual.
Understanding how default methods affect time helps you explain interface design choices clearly and shows you know how code runs as it grows.
"What if the default method called another method inside a loop? How would the time complexity change?"