Kotlin学习笔记3-3 类和对象-接口

接口

Kotlin官网:Classes and Objects-Interfaces
和Java8类似,既可以有抽象方法也可以有方法实现。
和抽象类的区别是不能保存状态,可以定义属性,属性可以是抽象的也可以实现访问器。
使用interface关键字声明。

interface MyInterface {
    fun bar()
    fun foo() {
      // optional body
    }
}

接口实现

一个类可以实现一个或多个接口。

class Child : MyInterface {
    override fun bar() {
        // body
    }
}

接口的属性

接口的属性既可以是抽象的也可以实现。
无法使用后备字段。

interface MyInterface {
    val prop: Int // abstract

    val propertyWithImplementation: String
        get() = "foo"

    fun foo() {
        print(prop)
    }
}

class Child : MyInterface {
    override val prop: Int = 29
}

重写冲突

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

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

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

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

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

C类只需实现bar方法,因为只有bar没有实现。接口中没有方法体的方法默认为abstract的。
对于继承多个接口的类,应该实现所有接口中的所有方法,指明实现类如何实现方法。如D要同时实现foo和bar两个方法,对于全部实现或是某几个接口实现的方法这个规则都适用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值