Sobes.tech
Junior — Middle

Can you explain the concept of inheritance in Kotlin and its main features?

sobes.tech AI

Answer from AI

Inheritance in Kotlin allows creating a new class based on an existing one, inheriting its properties and methods. By default, all classes in Kotlin are closed for inheritance (final), so to allow inheritance, a class must be declared with the open modifier.

Main features of inheritance in Kotlin:

  • A superclass must be declared with open or abstract.
  • A derived class uses the : keyword to specify the base class.
  • Constructors of the base class are called from the derived class.
  • Methods and properties that can be overridden must also be marked open.
  • The override keyword is used for overriding.

Example:

open class Animal(val name: String) {
    open fun sound() {
        println("Some generic animal sound")
    }
}

class Dog(name: String) : Animal(name) {
    override fun sound() {
        println("Woof!")
    }
}

fun main() {
    val dog = Dog("Buddy")
    dog.sound() // Outputs: Woof!
}
Can you explain the concept of inheritance in Kotlin… - sobes.tech