Kotlinインターフェースインターフェースはデフォルトでopenを実装しています。デフォルトの実装を提供できます

interface Movable {
    var maxSpeed: Int
    var wheels: Int
    fun move(movable: Movable): String
}

class Car(_name: String, override var wheels: Int = 4) : Movable {
    override var maxSpeed: Int
        get() = 1
        set(value) {}

    override fun move(movable: Movable): String {
    }

}

Kotlinの規制。すべてのインターフェイスのプロパティと関数は、overrideキーワードを使用する必要があります。インターフェイスで定義された関数は、openキーワードを変更する必要はありません。それらはデフォルトで開いています

デフォルトの実装

interface Movable {
    val maxSpeed: Int
        get() = (1..500).random()
    var wheels: Int
    fun move(movable: Movable): String
}

class Car(_name: String, override var wheels: Int = 4) : Movable {
    override var maxSpeed: Int
        get() = super.maxSpeed
        set(value) {}

    override fun move(movable: Movable): String {
        return "";
    }

}

fun main() {
    (1..100).forEach {
        println((1..3).random())
    }
}

 Javaとは異なります。Kotlinのインターフェースはデフォルトのパラメーターを実装できます。

おすすめ

転載: blog.csdn.net/mp624183768/article/details/123932123