Class definition in Java - Time & Space Complexity
When we define a class in Java, we want to know how much time it takes to create and use it.
We ask: How does the work grow when we make more objects from this class?
Analyze the time complexity of the following code snippet.
public class Box {
int length;
int width;
public Box(int length, int width) {
this.length = length;
this.width = width;
}
public int area() {
return length * width;
}
}
This code defines a simple Box class with a constructor and a method to calculate area.
Look for any repeated actions when using this class.
- Primary operation: Creating an object calls the constructor once.
- How many times: Each object creation runs the constructor once; area() runs once per call.
Think about making more boxes and calling area on each.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 constructor calls + 10 area calculations |
| 100 | 100 constructor calls + 100 area calculations |
| 1000 | 1000 constructor calls + 1000 area calculations |
Pattern observation: The work grows directly with the number of objects created and methods called.
Time Complexity: O(n)
This means if you create n boxes and call area on each, the total work grows in a straight line with n.
[X] Wrong: "Defining a class itself takes a lot of time as n grows."
[OK] Correct: Defining a class is done once and does not depend on n; only creating objects and calling methods depends on how many times you do it.
Understanding how object creation and method calls scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if the area() method had a loop inside? How would the time complexity change?"