Overriding methods with override in Kotlin - Time & Space Complexity
We want to see how the time it takes to run code changes when we use method overriding in Kotlin.
Specifically, how does calling an overridden method affect the work done as input grows?
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 playSounds(animals: List<Animal>) {
for (animal in animals) {
animal.makeSound()
}
}
This code defines a base class with a method, overrides it in a subclass, and calls the method on a list of animals.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling
makeSound()on each animal in the list. - How many times: Once for each animal in the list, so as many times as the list size.
Each animal in the list causes one method call. So if the list doubles, the calls double too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls |
| 100 | 100 method calls |
| 1000 | 1000 method calls |
Pattern observation: The work grows directly with the number of animals.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of animals.
[X] Wrong: "Overriding methods makes the program slower by a lot because it adds extra work."
[OK] Correct: Overriding just changes which code runs, but calling the method once per item stays the same. The extra work is very small and does not change how the total time grows.
Understanding how method calls scale helps you explain how your code behaves with more data. This shows you know how object-oriented features affect performance in real situations.
What if makeSound() called another method inside that loops over a list? How would the time complexity change?
Practice
Solution
Step 1: Understand method overriding rules in Kotlin
In Kotlin, methods are final by default and cannot be overridden unless marked otherwise.Step 2: Identify the keyword to allow overriding
Theopenkeyword is used in the parent class method to allow it to be overridden in subclasses.Final Answer:
open -> Option AQuick Check:
Parent method must beopento override [OK]
- Using 'override' in parent method instead of 'open'
- Forgetting to mark parent method as 'open'
- Using 'final' which prevents overriding
greet in a Kotlin subclass?Solution
Step 1: Recall syntax for overriding methods in Kotlin
To override a method, the subclass method must use theoverridekeyword.Step 2: Check each option
override fun greet() { println("Hello") } correctly usesoverride fun greet(). fun greet() { println("Hello") } missesoverride. open fun greet() { println("Hello") } usesopenwhich is for parent methods. final fun greet() { println("Hello") } usesfinalwhich prevents overriding.Final Answer:
override fun greet() { println("Hello") } -> Option BQuick Check:
Useoverridekeyword in subclass method [OK]
- Omitting 'override' keyword in subclass method
- Using 'open' instead of 'override' in subclass
- Marking subclass method as 'final' which disallows override
open class Animal {
open fun sound() = "Generic sound"
}
class Dog : Animal() {
override fun sound() = "Bark"
}
fun main() {
val pet: Animal = Dog()
println(pet.sound())
}Solution
Step 1: Understand method overriding and polymorphism
The variablepetis of typeAnimalbut holds aDogobject. The overriddensound()method inDogwill be called.Step 2: Determine output of
Sincepet.sound()Dogoverridessound()to return "Bark", the output will be "Bark".Final Answer:
Bark -> Option CQuick Check:
Overridden method runs based on actual object type [OK]
- Thinking output is from parent class method
- Confusing variable type with object type
- Expecting compilation or runtime errors
open class Vehicle {
fun start() = "Starting"
}
class Car : Vehicle() {
override fun start() = "Car starting"
}Solution
Step 1: Check if parent method allows overriding
Thestart()method inVehicleis not markedopen, so it cannot be overridden.Step 2: Identify the error in subclass
TheCarclass tries to overridestart()but parent method is not open, causing a compilation error.Final Answer:
Missing 'open' keyword on Vehicle's start method -> Option DQuick Check:
Parent method must be 'open' to override [OK]
- Forgetting to mark parent method as 'open'
- Trying to override non-open method
- Assuming 'override' alone allows overriding
main() is run?
open class Printer {
open fun print() = "Printing document"
}
class ColorPrinter : Printer() {
override fun print() = "Printing in color"
}
class PhotoPrinter : ColorPrinter() {
override fun print() = "Printing photo in color"
}
fun main() {
val printer: Printer = PhotoPrinter()
println(printer.print())
}Solution
Step 1: Understand class hierarchy and method overriding
PhotoPrinteroverridesprint()fromColorPrinter, which overridesPrinter's method.Step 2: Determine which method runs for
The variableprinter.print()printeris of typePrinterbut holds aPhotoPrinterobject, so the most derived override runs, which isPhotoPrinter.print().Final Answer:
Printing photo in color -> Option AQuick Check:
Most derived override runs based on actual object type [OK]
- Thinking parent class method runs instead of child's
- Confusing override chain in multi-level inheritance
- Expecting compilation error due to multiple overrides
Ready to prove it?
Pass the test and this pattern moves unknown
