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?"
Practice
open keyword do when applied to a class or method?Solution
Step 1: Understand Kotlin class and method defaults
By default, Kotlin classes and methods are final, meaning they cannot be inherited or overridden.Step 2: Role of the
Theopenkeywordopenkeyword explicitly allows a class to be inherited or a method to be overridden in subclasses.Final Answer:
Allows the class or method to be inherited or overridden -> Option CQuick Check:
openmeans inheritance allowed [OK]
- Thinking classes are open by default
- Confusing open with override
- Assuming open makes methods private
display in Kotlin?Solution
Step 1: Recall Kotlin method declaration syntax
In Kotlin, the keywordfunstarts the function declaration, followed by the function name and parentheses.Step 2: Position of
Theopenkeywordopenkeyword must come beforefunto mark the method as open for overriding.Final Answer:
open fun display() { } -> Option AQuick Check:
open funis correct order [OK]
- Placing open after fun
- Putting open after method name
- Using open without fun keyword
open class Animal {
open fun sound() = "Some sound"
}
class Dog : Animal() {
override fun sound() = "Bark"
}
fun main() {
val pet: Animal = Dog()
println(pet.sound())
}Solution
Step 1: Understand class inheritance and method overriding
The classDoginherits fromAnimaland overrides thesound()method to return "Bark".Step 2: Polymorphism in action
Even thoughpetis typed asAnimal, it holds aDoginstance, so the overriddensound()method inDogis called.Final Answer:
Bark -> Option BQuick Check:
Overridden method runs on subclass instance [OK]
- Expecting base class method output
- Confusing compile-time and run-time types
- Forgetting to mark methods open
class Vehicle {
open fun start() = "Starting"
}
class Car : Vehicle() {
fun start() = "Car starting"
}Solution
Step 1: Check if Vehicle class allows inheritance
By default, Kotlin classes are final. SinceVehicleis not markedopen, it cannot be inherited.Step 2: Analyze the inheritance attempt
Cartries to inherit fromVehicle, which causes a compilation error becauseVehicleis not open.Final Answer:
Vehicle class must be open to allow inheritance -> Option DQuick Check:
Classes must be open to inherit [OK]
- Forgetting to mark base class open
- Assuming methods override without keyword
- Ignoring Kotlin's default final classes
Shape with an open method area() that returns 0.0 by default. Then create a subclass Circle that overrides area() to return the circle's area using its radius. Which code correctly implements this?Solution
Step 1: Mark base class and method open
To allow inheritance and overriding,Shapemust beopenand itsarea()method must also beopen.Step 2: Override method correctly in subclass
Circleinherits fromShapeand overridesarea()usingoverridekeyword, calculating area using radius.Final Answer:
Option A code correctly implements open class and method with override -> Option AQuick Check:
Open base and override subclass method [OK]
- Not marking class or method open
- Missing override keyword in subclass
- Trying to override non-open method
Ready to prove it?
Pass the test and this pattern moves unknown
