Protected access modifier in Java - Time & Space Complexity
Let's explore how the protected access modifier affects the time complexity of method calls in Java.
We want to see how the program's work grows when using protected methods in inheritance.
Analyze the time complexity of the following code snippet.
class Parent {
protected void display() {
System.out.println("Parent display");
}
}
class Child extends Parent {
@Override
protected void display() {
super.display();
System.out.println("Child display");
}
}
public class Test {
public static void main(String[] args) {
Child c = new Child();
c.display();
}
}
This code shows a protected method called in a child class that overrides the parent method and calls it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Method calls to
display()in parent and child classes. - How many times: Called once in
main, no loops or recursion involved.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 2 method calls (parent and child) |
| 10 | 20 method calls if repeated 10 times |
| 100 | 200 method calls if repeated 100 times |
Pattern observation: The number of method calls grows linearly with how many times display() is called.
Time Complexity: O(n)
This means the work grows directly in proportion to how many times the protected method is called.
[X] Wrong: "Protected methods slow down the program because of access checks every time."
[OK] Correct: Access checks happen at compile time, not during each call, so runtime speed is not affected by the protected modifier.
Understanding how protected methods behave helps you explain inheritance and method overriding clearly, a key skill in many Java discussions.
What if the display() method was called inside a loop 1000 times? How would the time complexity change?
