【问题标题】:Kotlin / Java - Interface implementation + InheritanceKotlin / Java - 接口实现 + 继承
【发布时间】:2021-01-29 08:00:42
【问题描述】:

我有以下类和接口:

class A() {
    fun one() {...}
    fun two() {...}
}

class B(): A, C {
    fun tree() {...}
}

interface C {
    fun one()
    fun two()
    fun tree()
}

B 类可以扩展 A 并实现接口 C。 问题是,在 Kotlin 中,作为 C 的实际实现者的 B 类没有前 2 个函数,因此没有为接口实现正确的函数。 有没有正确的方法来做这样的事情?

【问题讨论】:

  • 您到底期待什么? A 类的one 和two 的实现满足接口契约。如果要覆盖它们,则需要在 A 类中标记函数open。当然,A 类本身必须标记为打开才能编译上述代码。
  • @Tenfour04 我不想覆盖它们,我希望它们满足界面但事实并非如此。我收到Class 'B' is not abstract and does not implement abstract member public abstract fun one()

标签: java kotlin inheritance interface


【解决方案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()
}

【讨论】:

    猜你喜欢
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多