英文:
Kotlin / Java - Interface implementation + Inheritance
问题
我有以下的类和接口:
class A() {
fun one() {...}
fun two() {...}
}
class B(): A, C {
fun tree() {...}
}
interface C {
fun one()
fun two()
fun tree()
}
正如你所看到的,类B继承了A并且还实现了接口C。
问题是,在Kotlin中,类B作为接口C的实际实现者,并没有拥有前两个函数,因此没有正确地实现接口所需的函数。
是否有一种正确的方法来做这样的事情?
英文:
I have the following classes and interface:
class A() {
fun one() {...}
fun two() {...}
}
class B(): A, C {
fun tree() {...}
}
interface C {
fun one()
fun two()
fun tree()
}
As you can class B extends A and also implements interface C.
The problem is that in Kotlin class B which is the actual implementor of C does not have the 2 first funcs and therefore not implementing the right functions for the interface.
Is there a right way to do such thing?
答案1
得分: 1
A
类需要标记为open
。- 类
B
的超类A
需要初始化(即A()
)。 B.tree()
方法需要使用override
修饰符。
除此之外,它应该可以工作...
open class A {
fun one() {}
fun two() {}
}
class B: A(), C {
override fun tree() {}
}
interface C {
fun one()
fun two()
fun tree()
}
英文:
- The
A
class needs to be markedopen
. - The super class
A
of the classB
needs to be initialized (i.e.A()
) - The
B.tree()
method requiresoverride
modifier
Apart of that, it should work...
open class A {
fun one() {}
fun two() {}
}
class B: A(), C {
override fun tree() {}
}
interface C {
fun one()
fun two()
fun tree()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论