kotlin エラー「error: cannot create an instance of an abstract class」の解決方法

kotlin エラー「error: cannot create an instance of an abstract class」の解決方法

kotlinで、エラー「error: cannot create an instance of an abstract class」の解決方法を記述してます。

環境

  • OS windows11 home
  • java 17.0.2
  • kotlin 1.6.10-release-923

エラー全文

以下のコードで発生。

abstract class Oya() {

    abstract fun f()    

}

class Ko() : Oya() {

    override fun f() { println("hello") }

}

fun main(){

    val oya = Oya()
    oya.f()

}

エラーメッセージ

error: cannot create an instance of an abstract class
    val oya = Oya()

原因

「抽象クラス」自体をインスタンス化しようとしているため

対処法

オーバーライドして、利用する

abstract class Oya() {

    abstract fun f()    

}

class Ko() : Oya() {

    override fun f() { println("hello") }

}

fun main(){

    val ko = Ko()
    ko.f() // hello

}