如何在 Kotlin 中建立一個抽象類的例項?


如果使用 abstract 關鍵字在 Kotlin 中定義了一個類,那麼則稱其為抽象類。在 Kotlin 中,我們不能建立抽象類的例項。抽象類只能被另一個本質上也是抽象的類實現。為了使用抽象類,我們需要建立一個新類並繼承抽象類。

示例 - Kotlin 中的抽象類

以下示例演示瞭如何在 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()
}

輸出

在執行時,它產生以下輸出 −

Implemented the abstract method

更新於: 2022 年 3 月 16 日

3 千次以上閱讀

開啟您的職業生涯生涯

完成課程取得認證

開始學習
廣告
© . All rights reserved.