Upcasting and downcasting in Java - Time & Space Complexity
We want to understand how the time it takes to run code changes when using upcasting and downcasting in Java.
Specifically, we ask: does casting affect how long the program runs as the input size grows?
Analyze the time complexity of the following code snippet.
class Animal { }
class Dog extends Animal { void bark() {} }
public class Main {
public static void main(String[] args) {
Animal[] animals = new Dog[1000];
for (int i = 0; i < animals.length; i++) {
animals[i] = new Dog(); // upcasting
}
for (Animal a : animals) {
Dog d = (Dog) a; // downcasting
d.bark();
}
}
}
This code creates an array of Dogs stored as Animals (upcasting), then converts each back to Dog (downcasting) to call a Dog method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two loops each running through the array of animals.
- How many times: Each loop runs once over all elements, so 1000 times in this example.
As the number of animals grows, the loops run more times, so the work grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (2 loops x 10) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: The total work grows directly with the number of elements, doubling the input doubles the work.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the number of elements processed.
[X] Wrong: "Casting objects takes extra loops or slows down the program significantly."
[OK] Correct: Casting is a simple check or reference change done once per object, it does not add extra loops or big work as input grows.
Understanding how casting fits into time complexity helps you explain performance clearly and shows you know what parts of code affect speed.
"What if we added a nested loop inside the downcasting loop to check each Dog against all others? How would the time complexity change?"