Kotlin 密封类
1.密封类用来表示受限的类继承结构:当一个值为有限集中的类型、而不能有任何其他类型时
2.密封类的一个子类可以有可包含状态的多个实例
3.要声明一个密封类,需要在类名前面添加
sealed修饰符4.所有子类都必须在与密封类自身相同的文件中声明
5.一个密封类是自身[抽象的],它不能直接实例化并可以有抽象(abstract)成员
6.密封类不允许有非-private 构造函数(其构造函数默认为 private)
7.扩展密封类子类的类(间接继承者)可以放在任何位置,而无需在同一个文件中
//表示
sealed class A
class AA: A() {
fun show1() {
println("AA_show")
}
}
class BB: A() {
fun show2() {
println("BB_show")
}
}
class CC: A() {
fun show3() {
println("CC_show")
}
}
fun show(a: A) {
when (a) {
is AA -> a.show1()
is BB -> a.show2()
is CC -> a.show3()
}
}
fun main() {
show(AA())
}