super Keyword in Kotlin
In Kotlin, the super keyword allows a subclass to access properties or methods from its parent class.
This is particularly useful when you override a method or property but still want to retain some behavior from the superclass.
super Keyword MattersYou can call a parent method using super.methodName():
open class Aircraft {
open fun startEngine() {
println("Engine started in parent Aircraft")
}
}
class Jet : Aircraft() {
override fun startEngine() {
super.startEngine() // Call parent method
println("Additional engine checks in Jet")
}
}
fun main() {
val jet = Jet()
jet.startEngine()
}
Output:
Engine started in parent Aircraft
Additional engine checks in Jet
You can also use super to access parent properties when overridden in a subclass:
open class Aircraft(open val type: String = "Generic")
class Jet : Aircraft("Jet") {
override val type: String = "Fighter Jet"
fun showTypes() {
println("Parent type: ${super.type}") // Parent property
println("Child type: $type") // Overridden property
}
}
fun main() {
val jet = Jet()
jet.showTypes()
}
Output:
Parent type: Generic
Child type: Fighter Jet
super with ConstructorsWhen a subclass inherits from a parent class with a primary constructor, super is used implicitly or explicitly to call the parent constructor:
open class Aircraft(val model: String)
class Jet(model: String, val maxSpeed: Int) : Aircraft(model) // Calls parent constructor
fun main() {
val jet = Jet("F-16", 1500)
println("Model: ${jet.model}, Max Speed: ${jet.maxSpeed}")
}
Output:
Model: F-16, Max Speed: 1500
super in Kotlin? super be used to call constructors? super implicitly or explicitly.super in overridden methods? super? super provides access to parent properties and methods.super ensures proper reuse and avoids code duplication.