How to extend and implement at the same time in Kotlin?n



In this article, we will take an example to demonstrate how we can extend and implement in the same class. In this example,

  • We will be creating an interface and a dummy Parent class.

  • From the Child class, we will extend the Parent class and implement the interface.

Example – Extending and implementing in child

interface myInterface {
   fun test(): String
}

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

class Child() : myInterface, myParentClass("ParentClass Input"){
   //child extending the parent class and implementing 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())
}

Output

Once you execute the code, it will produce the following output −

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

Advertisements