Skip to content

Kotlin Fundamentals: Inheritance

Devrath edited this page Jan 26, 2024 · 6 revisions

png (2)

Does kotlin supports multiple inheritance

No, Kotlin does not support multiple inheritance in the traditional sense, where a class can directly inherit from multiple classes. This is by design to avoid the complexities and issues associated with multiple inheritance, such as the diamond problem.

However, Kotlin provides a feature called "interface delegation" that allows a class to implement multiple interfaces. While this is not exactly the same as multiple inheritance, it allows you to achieve similar functionality by delegating the implementation of interfaces to other classes.

Here's an example:

interface A {
    fun methodA()
}

interface B {
    fun methodB()
}

class MyClass : A, B {
    private val implementationA = ClassA()
    private val implementationB = ClassB()

    override fun methodA() {
        implementationA.methodA()
    }

    override fun methodB() {
        implementationB.methodB()
    }
}

class ClassA : A {
    override fun methodA() {
        println("Implementation of methodA from ClassA")
    }
}

class ClassB : B {
    override fun methodB() {
        println("Implementation of methodB from ClassB")
    }
}

In this example, MyClass implements both interfaces A and B by delegating the actual implementations to instances of ClassA and ClassB. This way, you can achieve some level of code reuse and separation of concerns without directly inheriting from multiple classes.

Clone this wiki locally