美文网首页Kotlin编程
Kotlin 笔记 接口

Kotlin 笔记 接口

作者: yangweigbh | 来源:发表于2017-01-14 18:21 被阅读9次

kotlin的接口类似于Java 8中的接口,可以定义抽象函数,函数也可以有默认实现。它和抽象类的不同是接口不能存储状态。接口可以有属性,但是属性必须是抽象的或者提供访问方法的实现(要么没有实现,要么你自己提供实现,编译器不会帮你提供属性访问方法的实现)。

定义接口

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

实现接口

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

如果我们同时继承了两个接口,如果同名函数没有默认实现,或者有两个以上默认实现,子类需要显式overide函数,如果只有一个默认实现,则不需要显式overide

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()
    }
}

相关文章

网友评论

    本文标题:Kotlin 笔记 接口

    本文链接:https://www.haomeiwen.com/subject/hanebttx.html