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