接口用关键字 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() } } Mother Father 接口都有声明了 color() size() 函数。它们都实现了 color() 方法,但只有 Father 实现了 size() , size() 在 Mother 中并没有实现 它是抽象的,这是因为在接口中如果函数没有函数体,那么默认是抽象的。现在,如果我们从 Mother 中派生一个 Jones 实体类,显然我们需要重写 size() ,并实现它。而我们从 Mother 和 Father 派生一个 Cotton ,我们不用重写 size() 方法,因为我们的一个继承中有一个已经实现了它。但我们继承了两个 color() 的实现,因此编译器不知道应该选哪个,并强制我们重写 color() 并且明确指出我们具体想怎么实现,自己来重写。参考:http://www.kotlindoc.cn/ClassesAndObjects/Interfaces.html