Kotlin – 接口(Interface)
interface
用於聲明一個接口類:
interface Speakable{
fun say()
}
然後通過:
來實現接口,順帶說一下,在kotlin中,:
是一個很強大的符號,對應於Java的implements
、extends
都是用:
來實現:
class Bob : Speakable {
override fun say() = println("Hi, I'm Bob.")
}
正如你所見,在kotlin中override
對應的是Java的@override
。
在Kotlin中,接口類的方法還可以有默認的行爲(在Java中這個特性直到Java8才支持,而且需要用到default
關鍵字):
interface Speakable{
//常規方法聲明
fun say()
//帶有默認行爲的方法
fun sing() = println("Take me to your heart\nTake me to your soul")
}
當然,帶有默認行爲方法的接口也可以在其實現中重新覆寫其方法。
讓我們再來聲明另外一個接口,並且兩個接口都對其進行實現:
interface Speakable{
fun say()
fun sing() = println("Take me to your heart\nTake me to your soul")
}
interface Human{
fun sing() = print("Just Beat It Beat It Beat It Beat It")
}
class Bob : Speakable,Human {
override fun say() = println("Hi, I'm Bob.")
override fun sing() {
super<Speakable>.sing()
super<Human>.sing()
}
}
在這種情況下,他們兩個都包含了sing()
方法,如果你不指定其具體怎麼實現,那你會得到一個報錯:
Error:(17, 1) Kotlin: Class 'Bob' must override public open fun sing(): Unit defined in Kt04.Speakable because it inherits multiple interface methods of it
你可以在Bob
的sing()
方法指定具體實現哪個接口的sing()
方法,可以兩個默認方法都實現、或者只實現其中一個方法,也可以重新編寫自己的實現。如果只實現其中一個接口的方法,你可以這樣寫override fun sing() = super<Speakable>.sing()
因爲Kotlin 1.0 是基於Java6設計的,而Java6並不支持接口類的方法擁有默認行爲,所以當你在Java中使用帶有Kotlin的這一特性的Kotlin類時,你不得不再次手動在Java中重寫相關方法。