0
0
KotlinHow-ToBeginner · 3 min read

How to Use super in Kotlin: Syntax and Examples

In Kotlin, super is used to call a method or access a property from a superclass when it is overridden in a subclass. You write super.methodName() or super.propertyName inside the subclass to refer to the parent class implementation.
📐

Syntax

The super keyword lets you access members of the superclass from a subclass. Use it to call a superclass method or get/set a superclass property when you have overridden it.

  • super.methodName(): Calls the superclass version of a method.
  • super.propertyName: Accesses the superclass property.

This is useful when you want to extend or modify behavior but still use the original implementation.

kotlin
open class Parent {
    open fun greet() {
        println("Hello from Parent")
    }
}

class Child : Parent() {
    override fun greet() {
        super.greet() // Calls Parent's greet
        println("Hello from Child")
    }
}
💻

Example

This example shows a Child class overriding a method from Parent. It uses super.greet() to call the parent's method before adding its own message.

kotlin
open class Parent {
    open fun greet() {
        println("Hello from Parent")
    }
}

class Child : Parent() {
    override fun greet() {
        super.greet() // Calls Parent's greet
        println("Hello from Child")
    }
}

fun main() {
    val child = Child()
    child.greet()
}
Output
Hello from Parent Hello from Child
⚠️

Common Pitfalls

Common mistakes when using super include:

  • Trying to use super in a class that does not inherit from another class.
  • Calling super on a method or property that is not overridden or does not exist in the superclass.
  • Forgetting to mark superclass methods or properties as open to allow overriding.

Always ensure the superclass member is open and the subclass overrides it before calling super.

kotlin
open class Parent {
    fun greet() { // Not open, cannot override
        println("Hello from Parent")
    }
}

class Child : Parent() {
    // Error: Cannot override final member
    // override fun greet() {
    //     super.greet()
    //     println("Hello from Child")
    // }
}
📊

Quick Reference

super keyword usage summary:

UsageDescriptionExample
Call superclass methodInvoke overridden method from parentsuper.methodName()
Access superclass propertyGet or set property from parentsuper.propertyName
Use in constructorCall superclass constructorclass Child : Parent() { init { super.someMethod() } }
Requires open membersSuperclass methods/properties must be openopen fun greet() {}

Key Takeaways

Use super to call or access superclass members from a subclass.
Superclass methods or properties must be marked open to override and use super.
Calling super.method() lets you extend behavior instead of replacing it.
Avoid using super in classes without a superclass or on non-overridden members.