溫馨提示×

Kotlin抽象類能用于多態嗎

小樊
112
2024-11-05 09:13:05
欄目: 編程語言

是的,Kotlin 抽象類可以用于多態。在 Kotlin 中,多態是通過接口和抽象類實現的。抽象類可以包含抽象方法和非抽象方法,子類必須實現抽象方法。通過抽象類,我們可以定義一個通用的接口,然后讓不同的子類實現這個接口,從而實現多態。

下面是一個簡單的例子:

abstract class Shape {
    abstract fun area(): Double
}

class Circle(val radius: Double) : Shape() {
    override fun area(): Double {
        return Math.PI * radius * radius
    }
}

class Rectangle(val width: Double, val height: Double) : Shape() {
    override fun area(): Double {
        return width * height
    }
}

fun printShapeArea(shape: Shape) {
    println("The area of the shape is: ${shape.area()}")
}

fun main() {
    val circle = Circle(5.0)
    val rectangle = Rectangle(4.0, 6.0)

    printShapeArea(circle) // 輸出:The area of the shape is: 78.53981633974483
    printShapeArea(rectangle) // 輸出:The area of the shape is: 24.0
}

在這個例子中,我們定義了一個抽象類 Shape,它包含一個抽象方法 area()。然后我們創建了兩個子類 CircleRectangle,它們分別實現了 area() 方法。最后,我們定義了一個函數 printShapeArea,它接受一個 Shape 類型的參數,并調用其 area() 方法。在 main 函數中,我們創建了 CircleRectangle 的實例,并將它們傳遞給 printShapeArea 函數,實現了多態。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女