Parent and child classes in Java - Time & Space Complexity
When working with parent and child classes, it's important to understand how the program runs as the input grows.
We want to know how the time needed changes when we create or use many objects from these classes.
Analyze the time complexity of the following code snippet.
class Parent {
void greet() {
System.out.println("Hello from Parent");
}
}
class Child extends Parent {
void greet() {
System.out.println("Hello from Child");
}
}
public class Main {
public static void main(String[] args) {
Parent[] arr = new Parent[1000];
for (int i = 0; i < arr.length; i++) {
arr[i] = new Child();
arr[i].greet();
}
}
}
This code creates an array of child objects and calls a method on each one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that creates and calls greet() on each object.
- How many times: It runs once for each element in the array, so 1000 times in this example.
Each time we add more objects, the loop runs more times, doing more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 creations and 10 greet calls |
| 100 | 100 creations and 100 greet calls |
| 1000 | 1000 creations and 1000 greet calls |
Pattern observation: The work grows directly with the number of objects; doubling objects doubles the work.
Time Complexity: O(n)
This means the time needed grows in a straight line with the number of objects created and used.
[X] Wrong: "Since greet() is overridden, it might take longer for each call as n grows."
[OK] Correct: Each greet() call takes the same small amount of time regardless of how many objects exist; the number of calls matters, not the override.
Understanding how loops over objects affect time helps you explain program speed clearly and confidently.
"What if we added a nested loop inside the main loop that also iterates over the array? How would the time complexity change?"