Kotlin: Cannot create an instance of an abstract class
In this tutorial, we shall learn to fix Kotlin: Cannot create an instance of an abstract class.
Following is a sample of the error you might get during compilation.
Error:(2, 27) Kotlin: Cannot create an instance of an abstract class
Solution
In Kotlin, we cannot create an instance of an abstract class.
Abstract class could only be inherited by a class or another Abstract class. So, to use abstract class, create another class that inherits the Abstract class.
Following is an example that demonstrates the usage of kotlin abstract class.
Kotlin Program – example.kt
</>
Copy
/**
* Abstract Class
*/
abstract class Vehicle {
// regular variable
var name : String = "Not Specified"
// abstract variable
abstract var medium : String
// regular function
fun runsWhere() {
println("The vehicle, $name, runs on $medium")
}
// abstract function
abstract fun howItRuns()
}
/**
* inheriting abstract class
*/
class Aeroplane : Vehicle() {
// override abstract variables and functions of the
// abstract class that is inherited
override var medium: String = "air"
override fun howItRuns() {
println("Aeroplane fly based on buoyancy force.")
}
}
fun main(args: Array<String>) {
var vehicle1 = Aeroplane()
vehicle1.howItRuns()
}
Output
Aeroplane fly based on buoyancy force.