定义接口
接口使用interface关键字。
Kotlin 的接口类似于 java 8。可以包含抽象方法,以及方法的实现。和抽象类不同的是,接口不能保存状态;可以有属性但必须是抽象的 或 提供访问实现。
interfaceMyInterface { fun bar() fun foo() { // optional body } } |
实现接口
一个类 或 对象 可以实现一个或多个接口。
class Child :MyInterface { override fun bar() { // body } } |
接口中的属性
可以在接口中声明属性,属性必须是抽象的 或 提供访问实现。
interfaceMyInterface { val property: Int // abstract val propertyWithImplementation: String get() = "foo"
fun foo() { print(property) } }
class Child :MyInterface { override val property: 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() } } |
现在,如果我们从 A 中派生一个 C 实体类,显然我们需要重写bar() ,并实现它。 AB 接口都有声明了 foo() bar() 函数。它们都实现了 foo() 方法,但只有 B 实现了 bar() ,bar() 在 A 中并没有声明它是抽象的,这是因为在接口中如果函数没有函数体,那么默认是抽像的。