接口
Kotlin 中的接口和Java8中的很相似,既有抽象方法,又可以有实现。和抽象类不同的是,接口不能保存状态。可以有属性但必须是抽象的,或者提供访问器的实现。
接口用关键字 interface 来定义:
interface Mother {
fun color()
fun size() {
//函数体是可选的
}
}
接口的实现
一个类或对象可以实现一个或多个接口
class Jack:Mother{
fun color(){
//函数体是可选的
}
fun size() {
//函数体是可选的
}
}
接口中的属性
可以在接口中申明属性。接口中的属性要么是抽象的,要么提供访问器的实现。接口属性不可以有后备字段。而且访问器不可以引用它们。
interface Father {
val size: Int // abstract
val color: String
get() = "red"
fun take() {
print("size id $size color is $color.get()")
}
}
class Turner :Father {
override val size: Int = 29
}
解决重写冲突
当我们在父类中声明了许多类型,有可能出现一个方法的多种实现。比如:
interface Mother {
fun color() { print("red") }
fun size()
}
interface Father {
fun color() { print("blue") }
fun size() { print("180") }
}
class Jones : Mother {
override fun color() { print("red") }
}
class Cotton : Mother, Father {
override fun color() {
super<Mother>.color()
super<Father>.color()
}
}
参考:http://www.kotlindoc.cn/ClassesAndObjects/Interfaces.html