Junior — Middle
Kas Kotlinis on võimalik muuta päriliku klassi meetodi rakendust ilma muutmata selle meetodi lähdekoodi baasklassis?
sobes.tech AI
Vastus AI-lt
Yes, in Kotlin it is possible to change the implementation of a method in a derived class 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 print: Hello from Derived
}
This way, without changing the base class, the behavior of the method in the derived class can be changed.