Sobes.tech
Junior — Middle

Is it possible in Kotlin to change the implementation of a method in a subclass without modifying the source code of that method in the base class?

sobes.tech AI

Answer from AI

Yes, in Kotlin it is possible to change the implementation of a method in a subclass without modifying the source code of the base class, using the override mechanism. For this, the method in the base class must be declared with the open modifier.

Example:

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

class Derived : Base() {
    override fun greet() {
        println("Hello from Derived")
    }
}

fun main() {
    val obj: Base = Derived()
    obj.greet() // Will output: Hello from Derived
}

Thus, it is possible to change the behavior of a method in a subclass without modifying the base class.

Is it possible in Kotlin to change the implementation… - sobes.tech