Junior — Middle
How to implement inheritance for classes in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, to implement inheritance, a class must be declared with the open keyword to allow inheritance from it (by default, all classes are final). The inherited class is specified with a colon after the class name.
Example:
open class Animal(val name: String) {
open fun sound() {
println("Some sound")
}
}
class Dog(name: String) : Animal(name) {
override fun sound() {
println("Bark")
}
}
fun main() {
val dog = Dog("Buddy")
dog.sound() // Outputs: Bark
}
Here, Animal is the base class, Dog is the subclass that overrides the sound method. The override keyword is mandatory when overriding methods.