Sure, here is the translation: Kotlin / Java – 接口实现 + 继承

huangapple go评论113阅读模式
英文:

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

  1. A 类需要标记为 open
  2. B 的超类 A 需要初始化(即 A())。
  3. 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()
}
英文:
  1. The A class needs to be marked open.
  2. The super class A of the class B needs to be initialized (i.e. A())
  3. The B.tree() method requires override 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()
}

huangapple
  • 本文由 发表于 2020年10月15日 04:52:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64361340.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定