Kotlin 全面学习之路 (五) -- 接口

1、定义

和 Java 中一样,在 Kotlin 中使用关键字 interface 来定义接口:

interface OnclickLisenter{
  fun method()
}
2、接口实现

没什么好说明的,直接代码

class ViewClickListener :OnclickLisenter{
  override fun method(){
    //具体方法实现
  }
}
3、接口中的属性

在接口中声明接口的属性,需要注意以下两条:

  1. 接口的属性要么是抽象的,要么提供访问器实现
  2. 接口的属性不能有 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()
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值