- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 198字
- 2021-06-25 20:49:25
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!
推薦閱讀
- 手機(jī)安全和可信應(yīng)用開發(fā)指南:TrustZone與OP-TEE技術(shù)詳解
- Docker and Kubernetes for Java Developers
- PyTorch自動(dòng)駕駛視覺感知算法實(shí)戰(zhàn)
- Building a RESTful Web Service with Spring
- Koa開發(fā):入門、進(jìn)階與實(shí)戰(zhàn)
- Ray分布式機(jī)器學(xué)習(xí):利用Ray進(jìn)行大模型的數(shù)據(jù)處理、訓(xùn)練、推理和部署
- Python機(jī)器學(xué)習(xí)基礎(chǔ)教程
- 學(xué)習(xí)正則表達(dá)式
- 移動(dòng)界面(Web/App)Photoshop UI設(shè)計(jì)十全大補(bǔ)
- Unity 2017 Mobile Game Development
- Building Machine Learning Systems with Python(Second Edition)
- TMS320LF240x芯片原理、設(shè)計(jì)及應(yīng)用
- Android Development Tools for Eclipse
- C++程序設(shè)計(jì)教程
- 大話代碼架構(gòu):項(xiàng)目實(shí)戰(zhàn)版