Skip to content

Kotlin Fundamentals: Inheritance

Devrath edited this page Jan 27, 2024 · 6 revisions

png (2)

Does kotlin support 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 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:

Define the interfaces

interface KotlinInterfaceA { 
  fun methodA() 
}

interface KotlinInterfaceB { 
  fun methodB() 
}

Define the implementations for the interfaces

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

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

Define a new implementation for the interfaces, Where u create the implementation references and invoke the functions

class KotlinImplementation : KotlinInterfaceA, KotlinInterfaceB {

    private val implementationA = ClassA()
    private val implementationB = ClassB()

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

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

}
Clone this wiki locally