Overriding is a key feature of Object-Oriented Programming that allows a subclass to provide a specific implementation
for a method or property that is already defined in its superclass. Kotlin makes overriding explicit using the
open, override, and final keywords.
In Kotlin, methods are final by default, meaning they cannot be overridden unless explicitly marked as open in the parent class.
open class Aircraft(val name: String) {
open fun status() {
println("$name is ready for flight")
}
}
class Jet(name: String, val maxSpeed: Int) : Aircraft(name) {
override fun status() {
println("$name is ready for flight at max speed $maxSpeed km/h")
}
}
fun main() {
val jet = Jet("Falcon", 1200)
jet.status() // Calls overridden method
}
Output:
Falcon is ready for flight at max speed 1200 km/h
Note: Using override is mandatory; otherwise, the compiler will throw an error.
Kotlin allows properties to be overridden in subclasses, just like methods. Both val and var can be overridden if the parent property is open.
open class Aircraft {
open val type: String = "Generic Aircraft"
}
class Jet : Aircraft() {
override val type: String = "Jet Aircraft"
}
fun main() {
val jet = Jet()
println(jet.type) // Access overridden property
}
Output:
Jet Aircraft
- You can override a val property with a val or var in the subclass.
- You cannot override a var property with a val, as it would break mutability rules.
open class Aircraft {
open val speed: Int = 100
}
class Jet : Aircraft() {
override var speed: Int = 120 // Allowed: val -> var
}
Sometimes, you want to extend the behavior of a superclass method rather than completely replacing it. You can use super:
open class Aircraft(val name: String) {
open fun status() = println("$name ready")
}
class Jet(name: String, val maxSpeed: Int) : Aircraft(name) {
override fun status() {
super.status() // Calls Aircraft's status
println("Maximum speed: $maxSpeed km/h")
}
}
fun main() {
val jet = Jet("Falcon", 1200)
jet.status()
}
Output:
Falcon ready
Maximum speed: 1200 km/h
open in the superclass to allow overriding.open in the parent class and override in the subclass.val with val or var, but you cannot override var with val.super.methodName() inside the overridden method.open keyword is required to override.override keyword is mandatory in Kotlin to clearly indicate overriding.super to extend behavior instead of completely replacing it.val and var carefully handled.
open class ParentClass(open val name: String) {
open fun printName() {
println(name)
}
}
class ChildClass : ParentClass("Talha") {
override val name: String = "Usman" // Override property
override fun printName() {
println("${super.name} is the name of parent") // Access parent property
println("Overridden method: $name") // Access overridden property
}
}
fun main() {
val child = ChildClass()
child.printName()
}
Output:
Talha is the name of parent
Overridden method: Usman