今天來看 類別 / 初始化 / 繼承
class 結構
宣告 名稱 主要建構式 傳入參數
class ironman constructor(titleName: String, playerName: String){…}
主要建構式 constructor 可省略
class ironman(titleName: String, playerName: String){…}
無定義建構式參數的類別 / 初始化
var mNotParameter = ironmanNotParameter()
mNotParameter.printPlayerInfo()
class ironmanNotParameter constructor(){
//主要建構式 constructor()
//第二建構式
constructor(titleName: String):this()
//初始化
init{ println("Ithome 鐵人賽 2021")}
fun printPlayerInfo(){
println("Title: Kotlin Android 30天,從 0 到 ML , Player: Kevin ")
}
}
定義建構式參數的類別
var mPlayer = ironmanDefine()
mPlayer.mTitleName = "Kotlin Android 30天,從 0 到 ML"
mPlayer.mPlayerName = "Kevin"
mPlayer.printPlayerInfo()
class ironmanDefine {
var mTitleName:String = ""
var mPlayerName:String = ""
fun printPlayerInfo(){
println("Title: $mTitleName , Player: $mPlayerName ")
}
}
繼承類別
var mIronmanTitle = ironman("Kotlin Android 30天,從 0 到 ML", "Kevin")
mIronmanTitle.printPlayerInfo()
//繼承父類別要加 open
open class ironman constructor(titleName: String, playerName: String){
var mTitle = titleName
var mPlayer = playerName
open fun printPlayerInfo(){
println("Title: $mTitle , Player: $mPlayer ")
}
}
//多加一個開賽參數
var mIronPlayer = ironPlayer("Kotlin Android 30天,從 0 到 ML", "Kevin","9/6")
//覆寫父類別方法
mIronPlayer.printPlayerInfo()
//子類別方法
mIronPlayer.printironPlayerInfo()
//子類別繼承父類別,父類別前面要加 open
//子類別繼承父類別,子類別建構式多加參數
//子類別繼承父類別,子類別覆寫父類別方法
class ironPlayer constructor(titleName: String,
playerName: String,
var startDay:String
): ironman(titleName, playerName){
var mTitleName = super.mTitle
var mPlayerName = super.mPlayer
var mStartDay :String = startDay
override fun printPlayerInfo(){
println("override Title: $mTitleName , Player: $mPlayerName ")
}
fun printironPlayerInfo(){
println("Title: $mTitleName ,
Player: $mPlayerName , mStartDay = $mStartDay")
}
}
執行結果:
https://kotlinlang.org/docs/classes.html
https://kotlinlang.org/docs/inheritance.html