Kotlin Inheritance and final Keyword Tutorial

In this section, we will learn what the final keyword is and how to use it in Kotlin.

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

What is final keyword in Kotlin?

When creating a class, sometime we don’t want a specific class to become the super class or basically the parent class for other classes!

For this reason, Kotlin provided a keyword called final and if we prefix a class with this keyword, that class becomes a solo one which you can’t use it for the parent class of other classes.

Note: a final class can still become the child class and inherit from other classes, but it just can’t let other classes to inherit its members.

Note: by default, all classes are declared as final. So even if you don’t use the final keyword, that class already is set to final.

How to use the final keyword in Kotlin?

As mentioned before, we only need to prefix a class with the keyword final in order to stop it from becoming the parent class for other classes:

final class ClassName{…}

There’s no difference between the syntax above and the one below:

class ClassName{…}

Both are final in Kotlin.

Example: using the final keyword in Kotlin

open class GrandParent{
    fun sayHiParent(){
        println("Hello from parent class")
    }
}
final class FFClass: GrandParent(){
    fun sayHi(){
        println("Hello from the final class")
    }
}



fun main(){
    var fnl = FFClass()

    fnl.sayHi()
    fnl.sayHiParent()
}

Output:

Hello from the final class

Hello from parent class

How does final keyword work in Kotlin

In this example, the FFClass is declared as final and so even though the class itself is declared as the child of another class, we cannot use the FFClass as the parent of another class!

More to read:

Kotlin function overriding and final keyword

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies