How to create an instance of an abstract class in Kotlin?

Kotlin Mobile DevelopmentApps/Applications

When a class is defined in Kotlin with an abstract keyword, then it is known as an abstract class. In Kotlin, we cannot create an instance of an abstract class. Abstract classes can only be implemented by another class which should be abstract in nature. In order to use an abstract class, we need to create another class and inherit the abstract class.

Example – Abstract class in Kotlin

The following example demonstrates how you can create an instance of an abstract class in Kotlin.

abstract class myInter {
   abstract var absVariable : String
   abstract fun absMethod()
}
class myClass : myInter() {
   // we cannot create an instance of abstract class;
   // however we can implement the same functionality using another class
   override var absVariable: String = "Test"
   override fun absMethod() {
      println("Implemented the abstract method")
   }
}
fun main(args: Array<String>) {
   var obj = myClass()
   obj.absMethod()
}

Output

On execution, it will produce the following output −

Implemented the abstract method
raja
Updated on 16-Mar-2022 13:03:45

Advertisements