歡迎關(guān)注 二師兄Kotlin
轉(zhuǎn)載請注明出處 二師兄kotlin
Kotlin 的接口很像 java 8。它們都可以包含抽象方法,以及方法的實(shí)現(xiàn)。和抽象類不同的是,接口不能保存狀態(tài)??梢杂袑傩缘仨毷浅橄蟮?,或者提供訪問器的實(shí)現(xiàn)。
接口用關(guān)鍵字 interface 來定義:
interface MyInterface {
fun bar()
fun foo() {
// optional body
}
}
實(shí)現(xiàn)接口
一個(gè)類或?qū)ο罂梢詫?shí)現(xiàn)一個(gè)或多個(gè)接口
class Child : MyInterface {
override fun bar() {
// body
}
}
接口中的屬性
可以在接口中申明屬性。接口中的屬性要么是抽象的,要么提供訪問器的實(shí)現(xiàn)。接口屬性不可以擁有隱藏域(backing field),因此訪問器不可以引用它們。
interface MyInterface {
val prop: Int // abstract
val propertyWithImplementation: String
get() = "foo"
fun foo() {
print(prop)
}
}
class Child : MyInterface {
override val prop: Int = 29
}
解決重寫沖突
當(dāng)我們在父類中聲明了許多類型,有可能出現(xiàn)一個(gè)方法的多種實(shí)現(xiàn)。比如:
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()
}
}
A B 接口都有聲明了 foo() 和 bar() 函數(shù)。它們都實(shí)現(xiàn)了 foo() 方法,但只有 B 實(shí)現(xiàn)了 bar() ,bar() 在 A 中并沒有聲明它是抽象的,這是因?yàn)樵诮涌谥腥绻瘮?shù)沒有函數(shù)體,那么默認(rèn)是抽像的。
不過,如果我們從 A 中派生一個(gè) C 實(shí)體類,顯然我們需要重寫 bar() ,并實(shí)現(xiàn)它。而我們從 A 和 B 派生一個(gè) D ,我們不用重寫 bar() 方法,因?yàn)槲覀兊囊粋€(gè)繼承中有一個(gè)已經(jīng)實(shí)現(xiàn)了它。但我們繼承了兩個(gè) foo() 的實(shí)現(xiàn),因此編譯器不知道應(yīng)該選哪個(gè),并強(qiáng)制我們重寫 foo() 并且明確指出我們想怎么實(shí)現(xiàn)。