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

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.

主站蜘蛛池模板: 黑龙江省| 博乐市| 平南县| 安顺市| 洛隆县| 新乡市| 泗水县| 浦城县| 澄城县| 仙桃市| 黑河市| 阿荣旗| 禄丰县| 龙陵县| 民勤县| 鹿泉市| 昌宁县| 莎车县| 离岛区| 海城市| 长岛县| 军事| 翼城县| 合水县| 常德市| 聊城市| 白山市| 碌曲县| 上虞市| 西峡县| 大荔县| 永和县| 舒城县| 错那县| 绥阳县| 青神县| 格尔木市| 太仆寺旗| 丹棱县| 阿克苏市| 灌云县|