当前位置:   article > 正文

Kotlin基础教程-接口_kotlin sqlserverhelper

kotlin sqlserverhelper

kotlin-in-chinese
Interfaces

接口定义

关键字:interface

interface People {
    fun run()
}
  • 1
  • 2
  • 3

实现接口

interface People {
    fun run() 
}

class Chinese : People {
    override fun run() {}
}

class Japan : People {
    override fun run() {

    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

接口中属性

抽象属性

interface People {
    var age: Int//抽象属性
    fun run() {}//非抽象函数
}

class Chinese : People {
    override var age: Int
        get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
        set(value) {}

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

非抽象属性,要提供访问器

interface People {
    val age: Int
        get() = 1
    fun run() {}//非抽象函数
}

class Chinese : People {


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

实现多接口

interface A {
    fun foo() { print("A") }
    fun bar()
}

interface B {
    fun foo() { print("B") }
    fun bar() { print("bar") }
}



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

接口A中foo不是抽象函数,bar是抽象函数(),实现该接口的类必须实现bar(),所以实现A的类C的定义是下面这样的

class C : A {
    override fun bar() { print("bar") }
}
  • 1
  • 2
  • 3

C不用强制实现foo()


class D : A, B {
    override fun foo() {
        super<A>.foo()
        super<B>.foo()
    }

    override fun bar() {
        super<B>.bar()
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

由于A,B都有foo()bar()两个函数,所以类D中必须重写这个方法,如果不重写,编译器不知道使用哪个接口中的该方法。

super标识父类,或者实现的接口,泛型标识哪个父类,所以上面的代码中用super,super分别代表A,B中的函数

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/1009283
推荐阅读
相关标签
  

闽ICP备14008679号