Default access modifier in Java - Time & Space Complexity
Let's see how the default access modifier affects the time complexity of code access.
We want to know how the cost of accessing members changes with input size.
Analyze the time complexity of accessing a default access modifier member in a class.
class Box {
int width; // default access
int getWidth() {
return width;
}
}
public class Main {
public static void main(String[] args) {
Box box = new Box();
box.width = 10;
System.out.println(box.getWidth());
}
}
This code defines a class with a default access field and accesses it.
Look for repeated actions that affect time.
- Primary operation: Accessing the
widthfield and callinggetWidth(). - How many times: Once in this example, but could be many times if in a loop.
Accessing a field or method does not depend on input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 accesses if repeated 10 times |
| 100 | 100 accesses if repeated 100 times |
| 1000 | 1000 accesses if repeated 1000 times |
Pattern observation: Each access is constant time, so total time grows linearly with number of accesses.
Time Complexity: O(1)
This means accessing a default access field or method takes the same time no matter the input size.
[X] Wrong: "Accessing a default access field takes longer as the program grows."
[OK] Correct: Access time depends on the operation itself, not on how many other classes or files exist.
Understanding access modifiers helps you reason about code organization and performance clearly, a useful skill in many coding tasks.
What if the width field was declared private and accessed via a getter method? How would the time complexity change?
