Kotlin學習之-5.3 接口
Kotlin中的接口和Java 8中的接口很接近。它們可以定義抽象函數,也可以實現。和抽象類的區別在於接口不能存儲狀態。接口可以擁有屬性,但是這些屬性必須是抽象的或者提供訪問方法的實現。
接口使用關鍵字interface
來定義
interface MyInterface {
fun bar()
fun foo() {
// 可選的函數主體
}
}
實現接口
一個類或者一個對象可以實現一個或者多個接口
class Child: MyInterface {
override fun bar() {
// ...
}
}
接口中的屬性
可以在接口中定義屬性。在接口中定義屬性既可以是抽象的,也可以提供訪問方法的實現。定義在接口中的屬性不能有backing field,並且在接口中定義的訪問方法也不能引用他們。
interface MyInterface {
val prop: Int // 抽象的
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()
}
}
接口A和B都定義了foo()
和bar()
函數。它們倆都實現了foo()
,但是隻有B實現了bar()
, 在A中bar()
沒有被描述成抽象的,因爲當函數沒有主體時,這是接口的默認寫法。 現在如果我們繼承A來寫一個實體類C,必須複寫bar()
函數並提供它的實現。
然而,如果繼承A 和B 來寫類D,我們需要實現所有從接口中重複繼承的方法,並且寫明D 是如何實現他們的。這條規則既適用單繼承的方法,也適用於多繼承的方法。
PS,我會堅持把這個系列寫完,有問題可以留言交流,也關注專欄Kotlin for Android Kotlin安卓開發