Open classes and methods in Kotlin - Time & Space Complexity
Let's see how the time it takes to run code changes when we use open classes and methods in Kotlin.
We want to know how calling open methods affects the work the program does as it runs.
Analyze the time complexity of the following code snippet.
open class Animal {
open fun makeSound() {
println("Some sound")
}
}
class Dog : Animal() {
override fun makeSound() {
println("Bark")
}
}
fun playWithAnimals(animals: List) {
for (animal in animals) {
animal.makeSound()
}
}
This code defines an open class and method, then calls the method on a list of animals.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of animals and calling
makeSound()on each. - How many times: Once for each animal in the list (n times).
Each animal in the list causes one call to makeSound(). So, if the list grows, the work grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to makeSound() |
| 100 | 100 calls to makeSound() |
| 1000 | 1000 calls to makeSound() |
Pattern observation: The number of calls grows directly with the number of animals.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of animals increases.
[X] Wrong: "Because methods are open and can be overridden, calling them is slower and changes the time complexity."
[OK] Correct: Overriding methods does not change how many times the method is called. The loop still runs once per item, so the overall time grows the same way.
Understanding how method calls inside loops affect time helps you explain how your code scales. This skill shows you can think about performance clearly.
"What if the makeSound() method itself contained a loop over a list? How would that change the time complexity?"