Kotlin(6) 接口

6 Kotlin 接口

使用 interface 关键字定义接口,允许方法有默认实现:

interface MyInterface {
    fun bar()    // 未实现
    fun foo() {  //已实现
      // 可选的方法体
      println("foo")
    }
}

接口中的属性

interface MyInterface{
    var name:String //name 属性, 抽象的
}
 
class MyImpl:MyInterface{
    override var name: String = "runoob" //重写属性
}

函数重写

实现多个接口时,可能会遇到同一方法继承多个实现的问题。

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()
    }
}
发布了26 篇原创文章 · 获赞 0 · 访问量 1129

猜你喜欢

转载自blog.csdn.net/Plx0303sunny/article/details/103434965