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

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!
主站蜘蛛池模板: 香港 | 繁峙县| 大荔县| 本溪| 瓦房店市| 宝坻区| 井冈山市| 台东县| 潼南县| 安福县| 陆丰市| 瑞安市| 龙江县| 阿克苏市| 鲁甸县| 遂川县| 札达县| 长岭县| 威宁| 察哈| 余姚市| 华蓥市| 沿河| 象山县| 金乡县| 綦江县| 马关县| 班玛县| 辽阳县| 建德市| 咸宁市| 达日县| 广元市| 蓬安县| 深圳市| 古丈县| 江永县| 山阳县| 称多县| 上林县| 靖江市|