面试题答案
一键面试- 调用规则:
- 当一个类继承多个接口且这些接口有相同默认方法时,Kotlin 要求该类必须重写这个冲突的默认方法。这是因为编译器无法确定应该调用哪个接口的默认实现,所以需要开发者明确指定行为。
- 举例明确指定调用某个接口的默认方法:
interface InterfaceA {
fun commonMethod() = "From InterfaceA"
}
interface InterfaceB {
fun commonMethod() = "From InterfaceB"
}
class MyClass : InterfaceA, InterfaceB {
override fun commonMethod(): String {
// 明确调用 InterfaceA 的默认方法
return super<InterfaceA>.commonMethod()
}
}
fun main() {
val myObject = MyClass()
println(myObject.commonMethod())
}
在上述代码中,MyClass
实现了 InterfaceA
和 InterfaceB
两个接口,这两个接口都有 commonMethod
方法的默认实现。MyClass
重写了 commonMethod
方法,并通过 super<InterfaceA>.commonMethod()
明确指定调用 InterfaceA
的默认实现。如果想调用 InterfaceB
的默认实现,可写成 super<InterfaceB>.commonMethod()
。