Kotlin 中的Class 简单使用

本文详细介绍了Kotlin中的类特性,包括默认的final属性、抽象类的使用以及如何正确进行子类继承。示例中展示了open关键字用于允许继承,并通过with关键字简化代码。此外,还探讨了带有默认参数的构造函数,以及如何通过它来创建对象实例。
摘要由CSDN通过智能技术生成

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值