OOP principles overview in Java - Time & Space Complexity
We want to understand how the time it takes to run object-oriented programs grows as the program handles more data or objects.
How does using OOP principles affect the speed of our Java programs?
Analyze the time complexity of this simple Java class using OOP principles.
public class Counter {
private int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
This class uses encapsulation to manage a count value with simple methods to increase and get the count.
Look at what repeats when using this class in a program.
- Primary operation: Calling
increment()method to increase count. - How many times: Depends on how many times the method is called in the program.
Each call to increment() does a simple step, so the time grows directly with how many times we call it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The time grows in a straight line as we do more increments.
Time Complexity: O(n)
This means the time to run grows directly with the number of times we call the method.
[X] Wrong: "Using classes and objects always makes the program slower because of extra steps."
[OK] Correct: The extra steps are usually very small, and the main time depends on how many times methods run, not just on using OOP.
Understanding how OOP principles affect program speed helps you write clear code that also runs efficiently, a skill valued in many programming tasks.
What if the increment() method included a loop that runs through a list each time? How would the time complexity change?