Last active
October 2, 2022 15:35
-
-
Save espio999/b1e0ac77542a46bd1b56cb3dafa71b44 to your computer and use it in GitHub Desktop.
Abstract class and Interface, inheritance and override in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class BasicRole(name:String){ | |
var name = name | |
fun attack(){ | |
println("${name}は攻撃した") | |
} | |
open fun guard(){ | |
println("${name}は身を守っている") | |
} | |
fun run(){ | |
println("${name}は逃げ出した") | |
} | |
} | |
interface FighterSkill{ | |
fun doubleAttack(){} | |
} | |
interface MagicianSkill{ | |
fun magic(){} | |
} | |
interface PriestSkill{ | |
fun pray(){} | |
} | |
class Fighter(name:String):BasicRole(name), FighterSkill{ | |
override fun doubleAttack(){ | |
println("${name}の2回攻撃!") | |
this.attack() | |
this.attack() | |
} | |
override fun guard(){println("${name}の防御力強化")} | |
} | |
class Magician(name:String):BasicRole(name), MagicianSkill{ | |
override fun magic(){ | |
println("${name}は呪文を唱えた!") | |
} | |
} | |
class Priest(name:String):BasicRole(name), PriestSkill{ | |
override fun pray(){ | |
println("${name}は祈りをささげた!") | |
} | |
} | |
fun battle(party: List<BasicRole>, command: List<Int>){ | |
fun special(member: BasicRole){ | |
when(member){ | |
is Fighter -> member.doubleAttack() | |
is Magician -> member.magic() | |
is Priest -> member.pray() | |
} | |
} | |
for (i in 0..party.size - 1){ | |
when(command[i]){ | |
1->party[i].attack() | |
2->party[i].guard() | |
3->party[i].run() | |
else -> special(party[i]) | |
} | |
} | |
} | |
fun main(){ | |
val rhodesia = Fighter("ローデシア") | |
val sumaltria = Magician("サマルトリア") | |
val moonburg = Priest("ムーンブルグ") | |
val party: List<BasicRole> = listOf(rhodesia, sumaltria, moonburg) | |
battle(party, command=listOf(4, 4, 4)) | |
battle(party, command=listOf(2, 1, 3)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment