Kotlin 筆記 接口

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()
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容