Kotlin基本使用-抽象類及介面
阿新 • • 發佈:2019-01-05
Kotlin和Java一樣是單繼承多實現的
抽象類
Kotlin的抽象類和Java都是使用abstract,Kotlin可以是有抽象函式去覆蓋一個非抽象的公開函式。
open class Base {
open fun method(){
println("Base")
}
}
abstract class Example: Base(){
abstract override fun method()
}
介面
Kotlin的介面也是用 interface定義的,它可以有抽象的函式和實現的函式。
interface BaseInterface { fun method() fun method1(){ .... } }
介面中的屬性只能是抽象的或是提供訪問器實現(val修飾),介面的屬性是沒有幕後欄位的所以宣告的訪問器中是無法引用的
interface BaseInterface {
var attr: String
val attr1: String
get() = "attr1"
}
當實現多個介面的時遇到同一個函式繼承多個實現時,可以使用super< ? >指定要呼叫的函式。
interface BaseInterface { fun method(){ println("BaseInterface") } } interface Base { open fun method(){ println("Base") } } class Example: Base,BaseInterface { override fun method() { super<BaseInterface>.method() super<Base>.method() } }