kotlin中既继承又实现_Kotlin程序| 解决继承中的主要冲突的示例

kotlin中既继承又实现

继承中的主要冲突 (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.

    需要实现我们从多个接口继承的所有方法。

解决Kotlin中继承中的主要冲突 (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'


翻译自: https://www.includehelp.com/kotlin/example-of-resolving-overriding-conflicts-in-inheritance.aspx

kotlin中既继承又实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值