1、定义
和 Java 中一样,在 Kotlin 中使用关键字 interface
来定义接口:
interface OnclickLisenter{
fun method()
}
2、接口实现
没什么好说明的,直接代码
class ViewClickListener :OnclickLisenter{
override fun method(){
//具体方法实现
}
}
3、接口中的属性
在接口中声明接口的属性,需要注意以下两条:
- 接口的属性要么是抽象的,要么提供访问器实现
- 接口的属性不能有 backing field,所以在接口中声明的访问器不可以引用它们
具体示例:
interface ConInterface{
val name: String //抽象的
// 提供访问器实现
val propertyWithImplementation:: String
get() = "propertyWithImplementation:"
....
}
4、接口的继承
和 Java 中的概念基本一致,直接看代码:
interface Named {
val name: String
}
interface Person : Named {
val firstName: String
val lastName: String
override val name: String get() = "$firstName $lastName"
}
data class Employee(
// 不必实现“name”
override val firstName: String,
override val lastName: String,
val position: Position
) : Person
5、多实现引起的覆盖冲突
通过代码可以直观的有所了解:
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()
// 由于 bar() 只在 B 中实现了,所以不会引起冲突 ,则以下的写法正确
super.bar()
}
}