Kotlin基础教程-接口

kotlin-in-chinese
Interfaces

接口定义

关键字:interface

interface People {
    fun run()
}

实现接口

interface People {
    fun run() 
}

class Chinese : People {
    override fun run() {}
}

class Japan : People {
    override fun run() {

    }

}

接口中属性

抽象属性

interface People {
    var age: Int//抽象属性
    fun run() {}//非抽象函数
}

class Chinese : People {
    override var age: Int
        get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
        set(value) {}

}

非抽象属性,要提供访问器

interface People {
    val age: Int
        get() = 1
    fun run() {}//非抽象函数
}

class Chinese : People {


}

实现多接口

interface A {
    fun foo() { print("A") }
    fun bar()
}

interface B {
    fun foo() { print("B") }
    fun bar() { print("bar") }
}



接口A中foo不是抽象函数,bar是抽象函数(),实现该接口的类必须实现bar(),所以实现A的类C的定义是下面这样的

class C : A {
    override fun bar() { print("bar") }
}

C不用强制实现foo()


class D : A, B {
    override fun foo() {
        super<A>.foo()
        super<B>.foo()
    }

    override fun bar() {
        super<B>.bar()
    }
}

由于A,B都有foo()bar()两个函数,所以类D中必须重写这个方法,如果不重写,编译器不知道使用哪个接口中的该方法。

super标识父类,或者实现的接口,泛型标识哪个父类,所以上面的代码中用super,super分别代表A,B中的函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值