接口
Kotlin官网:Classes and Objects-Interfaces
和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()
}
}
C类只需实现bar方法,因为只有bar没有实现。接口中没有方法体的方法默认为abstract的。
对于继承多个接口的类,应该实现所有接口中的所有方法,指明实现类如何实现方法。如D要同时实现foo和bar两个方法,对于全部实现或是某几个接口实现的方法这个规则都适用。