- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 217字
- 2021-06-25 20:49:25
Constructors
Our DungeonMaster looks a bit awkward now, since it can proclaim the start of only one game. Let's add a non-empty constructor to our abstract class to fix that:
abstract class AbstractDungeonMaster(private val gameName : String) {
fun startGame() {
println("Game $gameName has started!")
}
}
Now, our DungeonMaster must receive the name of the game and pass it to the abstract class:
open class DungeonMaster(gameName: String):
Greeter, AbstractDungeonMaster(gameName)
What if we wanted to extend DungeonMaster by having an EvilDungeonMaster?
In Java, all classes can be extended, unless they're marked final. In Kotlin, no class can be extended, unless it's marked open. The same goes for functions in abstract classes. That's the reason why we declared DungeonMaster as open in the first place.
We'll change AbstractDungeonMaster a bit again to give more power to the evil ruler:
open fun startGame() {
// Everything else stays the same
}
Now, we add the following to our EvilDungeonMaster implementation:
class EvilDungeonMaster(private val awfulGame: String) : DungeonMaster(awfulGame) {
override fun sayHello() {
println("Prepare to die! Muwahaha!!!")
}
override fun startGame() {
println("$awfulGame will be your last!")
}
}
Whereas in Java, @Override is an optional annotation, in Kotlin it is a mandatory keyword.
You cannot hide supertype methods, and code that doesn't use override explicitly won't compile.
- Game Programming Using Qt Beginner's Guide
- CentOS 7 Linux Server Cookbook(Second Edition)
- Mastering Python Scripting for System Administrators
- Java持續(xù)交付
- 大學(xué)計(jì)算機(jī)基礎(chǔ)(第2版)(微課版)
- Building Minecraft Server Modifications
- 人人都懂設(shè)計(jì)模式:從生活中領(lǐng)悟設(shè)計(jì)模式(Python實(shí)現(xiàn))
- Expert Data Visualization
- 零基礎(chǔ)Java學(xué)習(xí)筆記
- LabVIEW虛擬儀器程序設(shè)計(jì)從入門到精通(第二版)
- UI設(shè)計(jì)全書(shū)(全彩)
- Android傳感器開(kāi)發(fā)與智能設(shè)備案例實(shí)戰(zhàn)
- Getting Started with Python and Raspberry Pi
- Image Processing with ImageJ
- 深入解析Java編譯器:源碼剖析與實(shí)例詳解