Kotlin 学习——接口

    Kotlin 的接口和 Java 8 类似,既包含抽象方法的说明,也包含实现,只是不能保存状态,它的属性必须声明为抽象或提供访问器实现:

interface Demo{
    fun show()
    fun look(){
        println("LOOK")
    }
}

class Child:Demo{
    override fun show() {
        
    }

    override fun look() {
        super.look()
    }

}

     在接口中定义的属性不能有幕后字段,因此接口中声明的访问器不能引用它们:

interface Demo{
    val name:String
    val age:Int
        get() = 20
    fun look(){
        println("$name:$age")
    }
}

class Child(override val name: String) :Demo{
    override fun look() {
        super.look()
    }
}

fun main(args: Array<String>) {
    val child = Child("宋琪飞")
    child.look()

}

    结果:


    接口继承:Kotlin 中的接口继承和类继承的写法一样,用法和 Java 中的接口比较类似,支持多继承,和 Kotlin 类不一样的是,Kotlin 的类是默认不能被继承的,可以使用 open 关键字使类可继承,但是 Kotlin 的接口是默认可继承的:

interface Father{
    fun show()
    fun look(){
        println("Father Look")
    }
}
class Son:Father{
    override fun show() {
        println("Son Show")
    }

    override fun look() {
        super.look()
        println("Son Look")
    }

}


fun main(args: Array<String>) {
    val son:Son = Son()
    son.show()
    son.look()
}

    结果:


    多继承时覆盖的冲突:我们可以使用 super<X> 来决定使用哪个父接口的方法:

interface Father{
    fun show(){
        println("Father Show")
    }
}
interface Mother{
    fun show(){
        println("Mother Show")
    }
}
class Son:Father,Mother{
    override fun show() {
        super<Father>.show()
        super<Mother>.show()
    }

}


fun main(args: Array<String>) {
    val son:Son = Son()
    son.show()
}

    结果:





猜你喜欢

转载自blog.csdn.net/young_time/article/details/80545492