假设我们有一个带有特征 A 的抽象类 A,我们还需要一个带有特征 B 扩展 A 的抽象类 B。稍后,我们创建一个带有扩展 A 的特征 C 的抽象类 C。
是否有可能以某种方式拥有一个具有特性 B 和 C 的抽象类,而无需重新实现(重写代码)其中之一?
abstract class A { fun featureA() { /* implementation */ } }
abstract class B: A() { fun featureB() { /* implementation */ } }
abstract class C: A() { fun featureC() { /* implementation */ } }
abstract class D: C() { fun featureB() { /* how can the implementation be avoided? */ } }
我不介意本身没有抽象类,但需要有相应功能的实现。
答案 0 :(得分:2)
你会使用接口吗?由于您确实想从类型 B
和 C
组合一个类,因此比尝试从两者继承更合适。您可以inherit from other interfaces并使用它们的实现:
interface A {
fun beA() { print("A!") }
}
interface B : A {
fun beB() { print("B!") }
}
interface C : A {
fun beC() { print("C!") }
}
class D : B, C {
fun beD() { print("D!") }
}
fun main() {
with(D()) {
beB()
beC()
beD()
beA()
}
}
>> B!C!D!A!
接口可以有属性,但不能有支持字段,所以它们必须是抽象的——你不能在接口中分配默认值。所以这是你可能会遇到的一个限制,而不是实际的抽象类。但是您可以使用 getter 函数创建属性:
interface A {
val luckyNumber = 777 // nope
val luckyNumber get() = 777 // yep
}