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

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.

主站蜘蛛池模板: 通道| 西林县| 南澳县| 永嘉县| 泗阳县| 富裕县| 黄陵县| 婺源县| 肥西县| 乡宁县| 广宗县| 柯坪县| 麻栗坡县| 深圳市| 河间市| 茶陵县| 阿拉善右旗| 应用必备| 融水| 林口县| 连城县| 观塘区| 甘南县| 兴化市| 桦甸市| 永福县| 长白| 东平县| 永善县| 伽师县| 关岭| 天水市| 安新县| 保德县| 涞源县| 高唐县| 方正县| 抚顺市| 呼图壁县| 焉耆| 临泉县|