The override Keyword
In this page:
Overriding a Function
Using override fun in a subclass replaces the base class's open implementation with a new one, and the keyword is mandatory in Kotlin, making overrides explicit and easy to spot.
Example: Overriding a Function
open class Shape {
open fun area(): Double = 0.0
}
class Square(val side: Double) : Shape() {
override fun area(): Double = side * side
}
fun main() {
val square = Square(4.0)
println("Area: ${square.area()}")
}
Login to try C/C++/Java/PHP code in the editor
Calling the Base Implementation with super
super.member inside an override calls the base class's original version, letting a subclass extend rather than completely replace the inherited behavior.
Example: Calling the Base Implementation with super
open class Logger {
open fun log(message: String) {
println("[LOG] $message")
}
}
class TimestampedLogger : Logger() {
override fun log(message: String) {
super.log("2024: $message")
}
}
fun main() {
val logger: Logger = TimestampedLogger()
logger.log("Application started")
}
Login to try C/C++/Java/PHP code in the editor
Overriding Properties
Properties can be overridden just like functions, using override val/override var, as long as the base property was declared open.
Example: Overriding Properties
open class Vehicle {
open val maxSpeed: Int = 100
}
class SportsCar : Vehicle() {
override val maxSpeed: Int = 300
}
fun main() {
val car: Vehicle = SportsCar()
println("Max speed: ${car.maxSpeed}")
}
Login to try C/C++/Java/PHP code in the editor
Preventing Further Overrides with final
Adding final before an override member prevents any further subclass from overriding it again, locking that particular behavior in place at this level of the hierarchy.
Example: Preventing Further Overrides with final
open class Base {
open fun greet() = "Hello from Base"
}
open class Middle : Base() {
final override fun greet() = "Hello from Middle"
}
fun main() {
val middle: Base = Middle()
println(middle.greet())
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting
overridewhen replacing an inherited open member; Kotlin requires it explicitly, unlike Java's optional@Override. - Using
overrideon a member that was not declaredopenin the base class, which the compiler rejects. - Forgetting to call
super.method()when the overriding method should extend, not fully replace, the base behavior.
- Kotlin requires the
overridekeyword whenever a subclass replaces an inherited open member. - The base member being overridden must itself be marked
open(or be an abstract/interface member). super.membercalls the base class's original implementation from within an override.- An overriding member is itself open for further overriding in a deeper subclass, unless marked
final.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: