Sobes.tech
Junior

How is inheritance implemented in Kotlin?

sobes.tech AI

Answer from AI

Inheritance in Kotlin is based on the keywords open and override. Classes and methods are final by default, meaning they cannot be inherited or overridden. To allow inheritance, a class or method must be marked with the open modifier.

To create a subclass, use a colon : after the name of the superclass, followed by the name of the base class with its constructor.

open class Base(val name: String) {
    open fun greet() {
        println("Hello, $name")
    }
}

To override a method of the base class in the subclass, use the override modifier.

class Derived(name: String) : Base(name) {
    override fun greet() {
        println("Greetings, $name")
    }
}

If the base class has a constructor with parameters, the subclass must call it using the super keyword.

Kotlin supports multiple inheritance of interfaces, but not classes. A class can inherit from only one other class.

A class can also mark its members as protected, internal, or private, limiting their visibility to subclasses or within the module respectively.

Abstract classes are declared with the abstract keyword. They can contain both abstract (without implementation) and regular methods. Abstract methods do not require the open keyword, as they are meant to be overridden. Abstract classes cannot be instantiated directly.

abstract class Shape {
    abstract fun draw()
    open fun printInfo() {
        println("This is a shape.")
    }
}

Thus, inheritance in Kotlin is explicitly controlled using the open and override modifiers, which enhances readability and prevents unwanted inheritance.

How is inheritance implemented in Kotlin? — Kotlin - sobes.tech