Calling Superclass / 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.

1. Why the super Keyword Matters

2. Basic Usage

You 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
  

3. Accessing Parent Properties

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
  

4. Using super with Constructors

When 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
  

5. Technical Interview Questions

6. Key Takeaways