如何在 Kotlin 中同时扩展和实现?

kotlin mobile developmentapps/applications

本文将通过一个示例演示如何在同一个类中扩展和实现。在本例中,

  • 我们将创建一个接口和一个虚拟的 Parent 类。

  • 从 Child 类开始,我们将扩展 Parent 类并实现该接口。

示例 - 在 child 类中扩展和实现

interface myInterface {
   fun test(): String
}

open class myParentClass(val name:String) {
   fun anotherTest():String {
      return name
   }
}

class Child() : myInterface, myParentClass("ParentClass Input"){
   //子类扩展父类并实现 myInterface
   override fun test(): String {
      return "This is implemented interface: myInterface"
   }
}

fun main(args : Array<String>) {
   println(Child().test())
   println("Reply from parent entity: "+myParentClass("hello parent").anotherTest())
}

输出

一旦执行代码,它将产生以下输出−

This is implemented interface: myInterface
Reply from parent entity: hello parent

相关文章