MST

星途 面试题库

面试题:Kotlin 中如何实现接口默认方法及重写

请描述在 Kotlin 中接口默认方法的定义方式,以及当一个类实现该接口时,重写默认方法的规则和语法。并给出一个简单示例代码。
18.5万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试

接口默认方法的定义方式

在 Kotlin 中,接口可以包含带默认实现的方法。通过在接口方法前使用 default 关键字来定义默认方法,示例如下:

interface MyInterface {
    fun doSomething() {
        println("This is the default implementation of doSomething")
    }
}

类实现接口时重写默认方法的规则和语法

  • 规则:类实现接口时,并不强制要求重写接口的默认方法。但如果类有需要,可以选择重写默认方法来提供自己的实现。
  • 语法:与重写普通接口方法类似,使用 override 关键字,示例如下:
class MyClass : MyInterface {
    override fun doSomething() {
        println("This is the overridden implementation of doSomething")
    }
}

简单示例代码

interface MyInterface {
    fun doSomething() {
        println("This is the default implementation of doSomething")
    }
}

class MyClass : MyInterface {
    override fun doSomething() {
        println("This is the overridden implementation of doSomething")
    }
}

fun main() {
    val myObject = MyClass()
    myObject.doSomething()
}

在上述示例中,MyInterface 定义了一个默认方法 doSomethingMyClass 实现了 MyInterface 并选择重写了 doSomething 方法。在 main 函数中创建 MyClass 的实例并调用 doSomething 方法,会执行重写后的逻辑。