- 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.
- 簡單高效LATEX
- Visual Basic程序設計習題解答與上機指導
- Easy Web Development with WaveMaker
- Building Minecraft Server Modifications
- Hands-On Functional Programming with TypeScript
- Python機器學習基礎教程
- D3.js 4.x Data Visualization(Third Edition)
- Learning ArcGIS for Desktop
- 零基礎看圖學ScratchJr:少兒趣味編程(全彩大字版)
- 跟戴銘學iOS編程:理順核心知識點
- 基于GPU加速的計算機視覺編程:使用OpenCV和CUDA實時處理復雜圖像數據
- Applied Deep Learning with Python
- 透視C#核心技術:系統架構及移動端開發
- AngularJS Web Application Development Cookbook
- MySQL數據庫應用技術及實戰