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
superin a class that does not inherit from another class. - Calling
superon a method or property that is not overridden or does not exist in the superclass. - Forgetting to mark superclass methods or properties as
opento 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:
| Usage | Description | Example |
|---|---|---|
| Call superclass method | Invoke overridden method from parent | super.methodName() |
| Access superclass property | Get or set property from parent | super.propertyName |
| Use in constructor | Call superclass constructor | class Child : Parent() { init { super.someMethod() } } |
| Requires open members | Superclass methods/properties must be open | open 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.