Junior — Middle
How can the behavior of a method in a class created based on another class be changed?
sobes.tech AI
Answer from AI
To change the behavior of a method in a class created based on another (inherited) class, the method overriding mechanism is used. A method with the same name and signature as in the base class is declared in the subclass, and new logic is implemented. When this method is called on an object of the subclass, the overridden version will be used.
Example in Kotlin (Android):
open class Animal {
open fun sound() {
println("Some generic sound")
}
}
class Dog : Animal() {
override fun sound() {
println("Bark")
}
}
fun main() {
val dog = Dog()
dog.sound() // Will output: Bark
}
Thus, overriding allows changing the behavior of a method inherited from the base class.