Sobes.tech
Junior — Middle

How can inheritance mechanism be implemented in Kotlin classes?

sobes.tech AI

Answer from AI

In Kotlin, the open keyword is used for the base class to enable inheritance, and : is used to specify inheritance.

By default, all classes in Kotlin are final (not inheritable), so the base class must be declared with open.

Example:

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

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

fun main() {
    val dog = Dog()
    dog.sound() // Outputs: Bark
}

Here, Dog inherits from Animal and overrides the sound method.

How can inheritance mechanism be implemented in… - sobes.tech