Google
 

星期四, 4月 21, 2022

Kotlin的繼承與override

 在Kotlin中若要override父類別的function, 則需要用override修飾字。

但若在父類別中沒有加修飾字, 則Kotlin會預設將此function視為final。

這時編譯器會出現這樣的錯誤:

[fun] in [parent class] is final and cannot be overriden 


解決方式是在父類別的function前加上open即可。

而在子類別中亦可用super.function名稱呼叫父類別的function。

如下:

fun main() {


    val squareCabin = SquareCabin(5)

    val roundHut = RoundHut(3)

    

    squareCabin.print()


    roundHut.print()

}


abstract class Dwelling(private var residents: Int) {

    abstract val buildingMaterial: String

    abstract val capacity: Int

       

    fun hasRoom(): Boolean {

       return residents < capacity

   }

    

   open fun print() {

        println("Capacity: ${capacity}")

        println("Material: ${buildingMaterial}")

        println("Has room? ${hasRoom()}")

    }

}


class SquareCabin(residents: Int) : Dwelling(residents) {

    override val buildingMaterial = "Wood"

    override val capacity = 6

    

    override fun print() {

        println("\nSquare Cabin\n==============")

        super.print()

    }

}


class RoundHut(residents: Int): Dwelling(residents) {

    override val buildingMaterial = "Straw"

    override val capacity = 4


    override fun print() {

        println("\nRound Hut\n==============")

        super.print()

    }

}


此外, 在宣告一個class後, 這個class預設為final的class, 是無法被繼承的。若class要能被繼承, 則需要在定義class時使用open修飾class, 如下:

open class RoundHut(residents: Int): Dwelling(residents) {

    override val buildingMaterial = "Straw"

    override val capacity = 4


    override fun print() {

        println("\nRound Hut\n==============")

        super.print()

    }

}


class RoundTower(residents: Int): RoundHut(residents) {

    override val buildingMaterial = "Stone"

    override val capacity = 4


    override fun print() {

        println("\nRound Tower\n==============")

        super.print()

    }

}


沒有留言: