面试题答案
一键面试接口默认方法的定义方式
在 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
定义了一个默认方法 doSomething
,MyClass
实现了 MyInterface
并选择重写了 doSomething
方法。在 main
函数中创建 MyClass
的实例并调用 doSomething
方法,会执行重写后的逻辑。