Sobes.tech
Junior — Middle

How can the behavior of methods be changed or supplemented when inheriting from a base class in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, the override keyword is used to modify or extend the behavior of methods in a base class during inheritance. The method in the base class must be declared with the open modifier to be overridden in a subclass.

Example:

open class Base {
    open fun greet() {
        println("Hello from Base")
    }
}

class Derived : Base() {
    override fun greet() {
        super.greet()  // call the base class method
        println("Hello from Derived")
    }
}

fun main() {
    val obj = Derived()
    obj.greet()
}

In this example, the greet method of the Base class is overridden in the Derived class, calling the original implementation via super.greet(), and then adding additional behavior.

Thus, to modify or extend the behavior of a method:

  • The method in the base class must be open.
  • The method in the subclass is marked with override.
  • You can call the original method via super to extend, not replace, the behavior.