0
0
KotlinHow-ToBeginner · 3 min read

How to Use the open Keyword in Kotlin for Inheritance

In Kotlin, the open keyword is used to allow a class or a function to be inherited or overridden because classes and functions are final by default. You add open before the class or function declaration to make it extendable.
📐

Syntax

The open keyword is placed before a class or function declaration to allow inheritance or overriding. By default, Kotlin classes and functions are final, meaning they cannot be extended or overridden.

  • open class ClassName { ... } - allows other classes to inherit from this class.
  • open fun functionName() { ... } - allows subclasses to override this function.
kotlin
open class Animal {
    open fun sound() {
        println("Animal sound")
    }
}

class Dog : Animal() {
    override fun sound() {
        println("Bark")
    }
}
💻

Example

This example shows how to use open to allow a class and its function to be extended and overridden. The Dog class inherits from Animal and overrides the sound function.

kotlin
open class Animal {
    open fun sound() {
        println("Animal sound")
    }
}

class Dog : Animal() {
    override fun sound() {
        println("Bark")
    }
}

fun main() {
    val animal: Animal = Dog()
    animal.sound() // Calls overridden method
}
Output
Bark
⚠️

Common Pitfalls

One common mistake is forgetting to mark a class or function as open when you want to inherit or override it. Without open, Kotlin classes and functions are final by default, so inheritance or overriding will cause a compile error.

Also, you must use override keyword when overriding an open function.

kotlin
class Animal {
    fun sound() {
        println("Animal sound")
    }
}

class Dog : Animal() {
    override fun sound() { // Error: Cannot override final member
        println("Bark")
    }
}

// Correct way:
open class AnimalOpen {
    open fun sound() {
        println("Animal sound")
    }
}

class DogCorrect : AnimalOpen() {
    override fun sound() {
        println("Bark")
    }
}
📊

Quick Reference

KeywordPurpose
open classAllows the class to be inherited
open funAllows the function to be overridden
override funOverrides an open function in a subclass
final (default)Prevents inheritance or overriding

Key Takeaways

Use open before classes or functions to allow inheritance or overriding.
Kotlin classes and functions are final by default, so open is required to extend them.
Always use override when overriding an open function in a subclass.
Forgetting open causes compile errors when trying to inherit or override.
Use final explicitly to prevent further inheritance or overriding if needed.