Kotlin Q & A

 

How do you implement inheritance in Kotlin?

In Kotlin, inheritance is implemented using the : symbol followed by the name of the superclass after the subclass declaration. Subclasses can inherit from only one superclass (single inheritance), but Kotlin supports multiple interface implementations.

Here’s a simple example of inheritance in Kotlin:

kotlin

open class Animal {
 open fun makeSound() {
 println("Animal makes a sound")
 }
}

class Dog : Animal() {
 override fun makeSound() {
 println("Dog barks")
 }
}

In this example, the Dog class inherits from the Animal class using the : Animal() notation. The makeSound() method is overridden in the Dog class to provide a specific implementation for dogs.

The open keyword is used in the superclass to indicate that its members can be overridden in subclasses. Conversely, subclasses can use the override keyword to override superclass members.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Experienced Android Engineer specializing in Kotlin with over 5 years of hands-on expertise. Proven record of delivering impactful solutions and driving app innovation.