In this section, we will learn what the super keyword is and how to use it in Kotlin.
Note: we’re assuming you’re already familiar with the function overriding in Kotlin.
What is super Keyword in Kotlin?
When overriding a function, you should know that the function in the parent class that we just overrode it won’t get invoke if we create an object from the child class and call the overridden method.
This is because of the way our program works, as explained in the Inheritance section (Programs start by looking at the child class and if they found the target function, they won’t go to the parent class looking for the same function!).
But if for whatever reason we want to also call the same function in the parent class, Kotlin provided a keyword called super
which represents the parent classes and we can use it to access to the parent class members.
Basically, by prefixing this keyword to the name of the parent member (property or function) that we have overridden, and call that member in the body of the child class, your program realizes that we want to access this member that belongs to the parent class and not the one that is declared in the child class! So it will jump into the closest ancestor class that has the target member and invoke that member.
Example: using super keyword in Kotlin
open class Parent{ open fun sayHi(){ println("Hello from the parent class") } } class Child: Parent() { override fun sayHi(){ super.sayHi() println("Hello from the child class") } } fun main(){ var child = Child() child.sayHi() }
Output:
Hello from the parent class Hello from the child class
How does super keyword work in Kotlin?
In this example, we have created an object from the Child class and called the sayHi()
function with it.
You can see that this function is overridden in the body of the Child class and so our program by default only invokes this function that we’ve set in this class.
But then we used the super
keyword and called the same function in the body of the overridden function.
This signals the program that we want the same method of the parent class to also be invoked.
As result, our program will jump into the parent class and run the body of that function as well and at the end return back to the body of the child function to continue and run the rest of instructions in this function too.