Skip to content

Kotlin Fundamentals: Inheritance

Devrath edited this page Feb 10, 2024 · 6 revisions

png (2)

Possible combinations of interface in kotlin

interface KotlinInterface {
    // ALLOWED
    fun printData()

    // NOT-ALLOWED:--> Function 'printData1' without body cannot be private
    //private fun functionDisplay()

    // ALLOWED:---> They will not be over-ridden the children class since it is private
    private fun functionSinging(){
        println("I am singing")
    }

    // NOT-ALLOWED:--> An interface may not have a constructor
    //constructor()

    // ALLOWED:--> Observe we have not initialized a value
    var anotherProperty: Int

    // NOT-ALLOWED:--> Interface properties are abstract by default, and the implementing class is responsible for providing concrete values for these properties.
    var nextProperty: Int = 5
}

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