What if you could change how a class works without rewriting it from scratch?
Why Open classes and methods in Kotlin? - Purpose & Use Cases
Imagine you want to add new features to a class someone else wrote, but the class is locked and you can't change it directly.
You try copying the whole class and changing it yourself, but that means repeating a lot of code and risking mistakes.
Manually copying and changing classes is slow and error-prone.
Every time the original class updates, you must copy changes again, which is frustrating and wastes time.
This approach makes your code messy and hard to maintain.
Open classes and methods let you extend or change behavior without copying code.
You can add new features by creating subclasses or overriding methods safely.
This keeps your code clean, easy to update, and flexible.
class Car { fun drive() { println("Driving") } } // To change drive, copy whole class and modify
open class Car { open fun drive() { println("Driving") } } class SportsCar : Car() { override fun drive() { println("Driving fast") } }
You can build on existing code easily, making your programs more powerful and adaptable.
Think of a video game where you want to create different types of characters based on a basic character class. Open classes let you create new characters with special moves without rewriting the whole character code.
Manual copying of classes is slow and risky.
Open classes and methods allow safe extension and modification.
This leads to cleaner, more maintainable, and flexible code.
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
