Kotlin 中的Class 简单使用

时间:2025-02-08 11:47:29

Kotlin 中的Class

文章目录

      • Kotlin 中的Class
        • 特点
          • abstract class
          • Subclass(子类)
            • 正确继承
            • 错误示范
            • 注意
          • Sample(例子)
            • Run and output(运行和输出)
          • 关键字
            • with
          • 多个参数的构造
            • Sample
            • Run and output(运行和输出)

特点

默认情况下,在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