Kotlin 中的Class 簡單使用
阿新 • • 發佈:2021-01-23
技術標籤:kotlin基礎
Kotlin 中的Class
文章目錄
特點
預設情況下,在Kotlin中,類是final類,不能子類化(被繼承),只允許繼承abstract class 或者被關鍵字open標記的class
abstract class
abstract class Dwelling(private var residents:Int) {
abstract val buildMaterial:String
abstract val capacity:Int
fun hasRoom():Boolean{
return residents < capacity
}
}
Subclass(子類)
class RoundHut(residents: Int) : Dwelling(residents) {
override val buildMaterial: String = "Stone"
override val capacity: Int = 4
}
正確繼承
open class RoundHut(residents: Int) : Dwelling(residents) {
override val buildMaterial: String = "Stone"
override val capacity: Int = 4
}
class RoundTower(residents: Int) : RoundHut(residents) {
override val buildMaterial: String = "Stone"
override val capacity: Int = 4
}
錯誤示範
This type is final, so it cannot be inherited from RoundHut
class RoundHut(residents: Int) : Dwelling(residents) {
override val buildMaterial: String = "Stone"
override val capacity: Int = 4
}
class RoundTower(residents: Int) : RoundHut(residents) {
override val buildMaterial: String = "Stone"
override val capacity: Int = 4
}
注意
定義抽象類時不需要使用open關鍵字, 因為當前表示abstract的,可以子類化的,修飾語open是多餘的
Sample(例子)
fun main(){
val roundTower = RoundTower(4)
with(roundTower){
println("\nRound Tower\n ====")
println("Material:${buildMaterial}")
println("Material:${capacity}")
println("Has room?${hasRoom()}")
}
}
Run and output(執行和輸出)
Round Tower
====
Material:Stone
Material:4
Has room?false
關鍵字
with
定義:以給定的[receiver]作為其接收方,呼叫指定的函式[block]並返回其結果
with後跟()中的例項名,後跟包含要執行的操作的{}
with(roundTower){
println("\nRound Tower\n ====")
println("Material:${buildMaterial}")
println("Material:${capacity}")
println("Has room?${hasRoom()}")
}
這裡[receiver] 是roundTower, {}裡為函式塊
多個引數的構造
class RoundTower(
residents: Int,
val floors: Int = 2) : RoundHut(residents) {
override val buildMaterial: String = "Stone"
override val capacity: Int = 4 * floors
}
其中建構函式中宣告 val floors: Int = 2 ,表示將floors賦值為2(預設值),當沒有將floors的值傳遞給建構函式時,可以使用預設值建立物件例項
Sample
val roundTower = RoundTower(4)
with(roundTower){
println("\nRound Tower\n ====")
println("Material:${buildMaterial}")
println("Material:${capacity}")
println("Has room?${hasRoom()}")
}
Run and output(執行和輸出)
Round Tower
====
Material:Stone
Material:8
Has room?true