Overriding methods and properties in Swift - Time & Space Complexity
When we override methods or properties in Swift, we want to know how this affects the time it takes for our program to run.
We ask: Does overriding change how long the program takes as it grows?
Analyze the time complexity of the following Swift code using method overriding.
class Animal {
func speak() {
print("Animal sound")
}
}
class Dog: Animal {
override func speak() {
print("Bark")
}
}
let pet: Animal = Dog()
pet.speak()
This code shows a base class with a method and a subclass that overrides it. We call the method on a subclass instance typed as the base class.
Look for repeated actions or calls that affect time.
- Primary operation: Calling the
speak()method once. - How many times: Exactly one time in this example.
Since the method is called once, the time does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays the same no matter how many objects or calls you have if you call the method once.
Time Complexity: O(1)
This means the time to run the overridden method call stays constant, no matter the input size.
[X] Wrong: "Overriding a method makes the program slower as input grows because it adds extra steps."
[OK] Correct: Overriding just changes which code runs, but calling the method still takes the same amount of time each call.
Understanding that overriding does not increase time complexity helps you explain how object-oriented features work efficiently in real programs.
"What if the overridden method calls a loop inside it? How would the time complexity change?"