Kotlin知识——接口


此博客主要讲解 Kotlin 语法,关于接口的更多内容可以查看: Java基础知识总结——接口

1、基础语法

Kotlin 中使用 interface 关键字声明接口:

interface Temp{
    
    
    fun test()
}

接口的实现:

class Realize: Temp{
    
    
    override fun test() = printIn("succeed")
}

注:在 Kotlin 中,在重写时使用 override 修饰符是强制要求的。

2、高级使用

在接口中定义带方法体的方法:

interface Temp1{
    
    
    fun test1()
    fun test2() = printIn("i am test2")
}

此时实现此接口可以不重写 test2 方法。

定义一个类似的接口:

interface Temp2{
    
    
    fun test3()
    fun test2() = printIn("i am test2, too")
}

定义一个类同时实现上述两个接口,因为两个接口都实现了 test2 方法,故该类需要显示地实现 test2 方法:

class Realize: Temp1, Temp2{
    
    
    override fun test1() = printIn("test1")
    override fun test2(){
    
    
        //使用尖括号加父类型名字的“super”表明想要调用哪一个父类方法
        super<Temp1>.test2()
        super<Temp2>.test2()
    }
    override fun test3() = printIn("test3")
}

注:没有显示实现 test2 会引发编译错误。

Guess you like

Origin blog.csdn.net/qingyunhuohuo1/article/details/111224848