官术网_书友最值得收藏!

Inheritance

Exactly like in Java, abstract classes are marked by abstract and interfaces by the interface keyword:

abstract class AbstractDungeonMaster {
abstract val gameName: String

fun startGame() {
println("Game $gameName has started!")
}
}

interface Dragon

As in Java 8, interfaces in Kotlin can have a default implementation of functions, as long as they don't rely on any state:

interface Greeter {
fun sayHello() {
println("Hello")
}
}

There are no inherits and implements keywords in Kotlin. Instead, both the name of an abstract class and all the names of the interfaces that class implements are put after a colon: 

class DungeonMaster: Greeter, AbstractDungeonMaster() {
override val gameName: String
get() = "Dungeon of the Beholder"
}

We can still distinguish the abstract class by the parenthesis that comes after its name, and there can still be only one abstract class, as there are no multiple inheritances in Kotlin.

Our DungeonMaster has access to both functions from Greeter and AbstractDungeonMaster:

val p = DungeonMaster()
p.sayHello() // From Greeter interface
p.startGame() // From AbstractDungeonMaster abstract class

Calling the preceding code, it will print the following output:

Hello
Game Dungeon of the Beholder has started!
主站蜘蛛池模板: 木里| 紫金县| 信丰县| 屏南县| 长海县| 东光县| 东至县| 定襄县| 延川县| 南充市| 长沙市| 西峡县| 望城县| 波密县| 安岳县| 新竹县| 舞钢市| 潞城市| 柯坪县| 抚顺市| 枣阳市| 喀喇沁旗| 子洲县| 三河市| 枣庄市| 格尔木市| 望奎县| 东莞市| 罗定市| 和田县| 绥德县| 容城县| 二连浩特市| 天台县| 武鸣县| 辽源市| 沈阳市| 西安市| 凤阳县| 凤台县| 图木舒克市|