Kotlin学习笔记 第二章 类与对象 第十一节 枚举类 第八节密封类

本文详细介绍了Kotlin中枚举类和密封类的基础用法、构造函数、成员变量与方法、抽象方法实现、接口实现以及switchcase的使用。通过实战案例对比了两者在限制继承结构和状态管理上的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考链接

Kotlin官方文档

https://kotlinlang.org/docs/home.html

中文网站

https://www.kotlincn.net/docs/reference/properties.html

本系列为参考Kotlin中文文档

https://download.youkuaiyun.com/download/u011109881/21418027

整理的笔记 

pdf也可以在这里下载

https://www.kotlincn.net/docs/kotlin-docs.pdf

因为密封类与枚举类关系比较紧密 临时调整学习顺序 先学习枚举类 再学习密封类

第二章 第十一节 枚举类

知识点

1 枚举类的基本用法

2 构造函数带参数的枚举

3 枚举类型可以定义成员变量与方法

4 枚举类实现抽象方法

5 在枚举类中实现接口

6 枚举的switch case

笔记

fun main() {
    // 1 枚举类的基本用法
    println(Direction.EAST)
    // 每种枚举类型都是一个枚举的类的类型
    println(Direction.EAST is Direction)

    // 2 构造函数带参数的枚举
    println(Color.BLUE)
    println(Color.BLUE.rgb)

    // 3 枚举类型可以定义成员变量与方法
    Color2.BLUE.test()
    Color2.BLUE.property = "property"
    println(Color2.BLUE.property)

    // 4 枚举类实现抽象方法
    println(ProtocolState.TALKING.signal())
    println(ProtocolState.WAITING)

    // 5 在枚举类中实现接口
    println(EnumImplInterface.PLUS)

    // 6 枚举的switch case
    val driver1 = Driver(LicenseStatus.UNQUALIFIED);
    println(driver1.checkLicense())
    val driver2 = Driver(LicenseStatus.LEARNING);
    println(driver2.checkLicense())
}

// 6 枚举的switch case
enum class LicenseStatus {
    UNQUALIFIED,
    LEARNING,
    QUALIFIED;
}

class Driver(var status: LicenseStatus) {
    fun checkLicense(): String {
        return when (status) {
            LicenseStatus.LEARNING -> "在学"
            LicenseStatus.QUALIFIED -> "有资格"
            LicenseStatus.UNQUALIFIED -> "没有资格"
        }
    }
}

// 5 在枚举类中实现接口
interface IAdd {
    fun add(a: Int, b: Int): Int
    fun sub(a: Int, b: Int): Int
}

enum class EnumImplInterface() : IAdd {
    PLUS,
    SUB;

    override fun add(a: Int, b: Int): Int {
        return a + b
    }

    override fun sub(a: Int, b: Int): Int {
        return a - b
    }
}

// 4 枚举类实现抽象方法
enum class ProtocolState {
    WAITING {
        override fun signal() = "WAITING"
    },

    TALKING {
        override fun signal() = "TALKING"
    };

    abstract fun signal(): String
}

// 3 枚举类型可以定义成员变量与方法
enum class Color2() {
    RED,
    GREEN,
    BLUE;

    fun test() {
        println("test")
    }

    var property: String = ""
}

// 2 构造函数带参数的枚举 带有一个属性 rgb
enum class Color(val rgb: Int) {
    RED(0xFF0000),
    GREEN(0x00FF00),
    BLUE(0x0000FF)
}

// 1 枚举类的基本用法
enum class Direction {
    // Kotlin 种的枚举也是一个类
    NORTH, SOUTH, WEST, EAST
}

class D0311EnumClass 

第二章 第八节密封类

知识点

1 密封类

2 继承自密封类

3 密封类中switch case的使用

4 密封类 实战2

5 总结 密封类vs枚举类

笔记

fun main() {
    // 1 密封类
    // 密封类用来表示受限的类继承结构:当一个值为有限几种的类型、而不能有任何其他类型时。
    // 在某种意义上,他们是枚举类的扩展:枚举类型的值集合也是受限的,但每个枚举常量只存在一个实例,而密封类的一个子类可以有可包含状态的多个实例。
    // 简而言之 枚举类里面的各种case是单例 但是密封类的各种case不一定是单例

    // 2 继承自密封类
    // val a = Expr() //密封类本身是抽象的 不能实例化
    val b = Const(12.0)
    val c = Sum(b, b)
    val d = NotANumber
    val e = NotANumber
    println(d === e)

    // 3 密封类中switch case的使用
    // 使用密封类的关键好处在于使用 when 表达式 的时候,如果能够验证语句覆盖了所有情况,就不需要为该语句再添加一个 else 子句了。
    // 当然,这只有当你用 when 作为表达式(使用结果)而不是作为语句时才有用。
    println(eval(Const(16.1)))
    println(eval(Sum(Const(16.1), Const(13.9))))
    println(eval(NotANumber))

    // 4 密封类 实战2 该案例参考自bilibili动脑学院P102密封类
    val status: LicenseStatus2 = LicenseStatus2.Learning
    val driver = Driver2(status)
    println(driver.checkLicense())
    val driver2 = Driver2(LicenseStatus2.Qualified("12345"))
    println(driver2.checkLicense())

    // 5 总结 密封类vs枚举类
    // 枚举类每个类型都是单例 密封类每个类型可以是单例也可以不是 相比于枚举类 密封类更加灵活
}

// 4 密封类 实战2
sealed class LicenseStatus2 {
    object UnQualified : LicenseStatus2()// 密封类子类 单例 无状态
    object Learning : LicenseStatus2()// 密封类子类 单例 无状态

    // 可以有多个实例 licenseId是一个状态 不同driver的licenseId可以不一样
    class Qualified(val licenseId: String) : LicenseStatus2()
}

class Driver2(var status: LicenseStatus2) {
    fun checkLicense(): String {
        return when (status) {
            is LicenseStatus2.Learning -> "在学"
            is LicenseStatus2.UnQualified -> "没有资格"
            is LicenseStatus2.Qualified -> "有驾驶证. 驾驶证编号:${(this.status as LicenseStatus2.Qualified).licenseId}"
        }
    }
}

// 3 密封类种switch case的使用
fun eval(expr: Expr): Double = when (expr) {
    is Const -> expr.number
    is Sum -> eval(expr.e1) + eval(expr.e2)
    NotANumber -> Double.NaN
    // else -> 0.0 // 'when' is exhaustive so 'else' is redundant here
    // 不再需要 `else` 子句,因为我们已经覆盖了所有的情况
}


// 密封类不允许有非-private 构造函数(其构造函数默认为 private)
sealed class Expr1(parameter: String) {
    // Constructor must be private or protected in sealed class
    // public constructor(parameter: String, parameter2: String) : this(parameter)
}

// 2 继承自密封类
// 密封类
// 虽然密封类也可以有子类,但是所有子类都必须在与密封类自身相同的文件中声明
// 注意,扩展密封类子类的类(间接继承者)可以放在任何位置,而无需在同一个文件中。
sealed class Expr

// 数据类继承密封类
data class Const(val number: Double) : Expr()

// 数据类继承密封类
data class Sum(val e1: Expr, val e2: Expr) : Expr()

// 单例继承密封类
object NotANumber : Expr()

class D0308SealedClass

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值