most from reference
Kotlin中的接口非常类似于Java8,它们可以包含抽象方法的声明以及方法实现。与抽象类不同的是接口不能存储状态。它们可以具有属性,但这些需要是抽象的或提供访问器。 使用interface关键字定义接口
interface MyInterface { fun bar() fun foo() { // optional body } }类或对象可以实现一个或多个接口
class Child : MyInterface { override fun bar() { // body } }您可以在接口中声明属性。在接口中声明的属性可以是抽象的,也可以实体访问器。在接口中声明的属性不能有后备字段,因此在接口中声明的访问器不能引用他们。
interface MyInterface { val prop: Int // abstract val propertyWithImplementation: String get() = "foo" fun foo() { print(prop) } } class Child : MyInterface { override val prop: 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() } override fun bar() { super<B>.bar() } }接口A和B都声明了函数foo()和bar(),它们都实现了foo(),但只有B实现了bar()(bar()在A中没有标记为abstract,因为如果没有函数体,这是函数的默认值)。现在,如果我们定义一个类C实现A接口,我们必须重写bar()并提供一个实现。 然而,如果我们定义一个类D实现A和B接口,我们需要实现多个接口所有的方法,并指定D应该如何实现它们。此规则既适用于继承单个实现(bar())和多个实现(foo())的方法。
