Q:

Kotlin program | Example of Resolving Overriding Conflicts in Inheritance

belongs to collection: Kotlin Class and Object Programs

0

Overriding Conflicts in Inheritance

  • It may appear, we inherit more than one implementation of the same method.
  • Need to implement all the methods which we have inherited from multiple interfaces.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Resolving Overriding Conflicts in Inheritance in Kotlin

package com.includehelp

// declare interface
interface One{
    // abstract function
    fun myName()

    // function with implementation
    fun sayHello(){
        println("Hello, 'From Interface One' ")
    }
}

interface Two{
    // function with implementation
    fun sayHello(){
        println("Hello, 'From Interface Two' ")
    }

    // function with implementation
    fun myName(){
        println("My Name is  Interface 'Two'")
    }
}

// class implementing interface
class Three:One{
    // override interface abstract method
    override fun myName() {
        println("My Name is Class Three")
    }
}

// class implementing more then one interfaces
class Four:One,Two{

    // need to implement all the methods 
    // which we have inherited from multiple interfaces
    override fun sayHello() {
        // Both interface have sayHello implementation in interfaces,
        // so explicitly define Interface name in super to call, 
        // specific implementation from class
        super<One>.sayHello()
        super<Two>.sayHello()
        println("Hello, From Class 'Four' ")
    }

    // need to implement all the methods 
    // which we have inherited from multiple interfaces
    override fun myName() {
        // called super type implementation of method,
        // only interface two have implementation of this method, 
        // so need to explicitly define interface name
        super.myName()

        println("My Name is Class Four")
    }

}

// Main function, Entry point of program
fun main(){
    // create class instance
    val four = Four()
    // call methods
    four.myName()

    // call methods
    four.sayHello()
}

Output:

My Name is  Interface 'Two'
My Name is Class Four
Hello, 'From Interface One' 
Hello, 'From Interface Two' 
Hello, From Class 'Four'

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin program | Example of Overriding Properties... >>
<< Kotlin program | Example of Inheritance within Int...