Kotlin Function Overriding Tutorial

In this section, we will learn what function overriding is and how it works in Kotlin.

Note: we’re assuming you’re already familiar with the Kotlin Inheritance.

What is Function Overriding in Kotlin?

Function overriding is the process of creating an exact function (with exact signature) that is already created in a parent class, inside the body of a child class.

This is mainly used when there’s a function in a parent class that has the right name and parameters, but the instructions within its body are not what we’re looking for! So we can override that function in the body of a child class and design our own body instead.

Kotlin Function Overriding Declaration Syntax:

In order to override a function, it must be prefixed with the keyword open when creating it in the parent class.

For example:

open fun functionName(){…}

Now we can override this function in the body of a child’s class.

Example: overriding a function in Kotlin

open class Parent{
    open fun sayHi(){
        println("Hello from the parent class")
    }
}

class Child: Parent() {
    override fun sayHi(){
        println("Hello from the child class")
    }
}

fun main(){
    var child = Child() 
    child.sayHi()
}

Output:

Hello from the child class

How does function overriding work in Kotlin?

In the example above, the sayHi function is defined in the Parent class. If we look at its body, we can see that it is sending the message “…from Parent class” to the output stream! This means even if we create an object using the Child class, we still get this message.

So now if we want to change the body of the function and create another function with the same signature in the body of the Child class, all we need to do is to prefix the sayHi function with the keyword open and then override the function in the child class using the override keyword.

Kotlin function overriding and the final keyword

If we don’t want a function to be overridden by a child class, we can prefix that using the final keyword.

Note, however, that functions by default are set to final and that means if we don’t explicitly turn them into open, they can’t be overridden.

Example: using final keyword in Kotlin function overriding

open class Parent{
    final fun sayHi(){
        println("Hello from the parent class")
    }
}

class Child: Parent() {
    override fun sayHi(){
        println("Hello from the child class")
    }
}

fun main(){
    var child = Child() 
    child.sayHi()
}

Output:

error: 'sayHi' in 'Parent' is final and cannot be overridden

As you can see, the sayHi function in the Parent class is explicitly set to final, and that means we can’t override such function in the body of the child class anymore.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies