-
Notifications
You must be signed in to change notification settings - Fork 24
Kotlin Fundamentals: Inheritance
Devrath edited this page Jan 27, 2024
·
6 revisions
- 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.
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()
}
}