sealed class MySealedPersonSex {

/**

  • MySealedPersonSex的>>> 类 男人👱

*/

class Man(var name:String, var age:Int) {

/**

  • 打印姓名和年龄的方法

*/

fun showNameAge() {

println(“这为男人的 姓名是:name,年龄是{name}, 年龄是name,年龄是{age}岁”)

}

}

/**

  • MySealedPersonSex的>>> 类 女人👩

*/

class WoMan(var name:String, var age:Int) {

/**

  • 打印姓名和年龄的方法

*/

fun showNameAge() {

println(“这为女人的 姓名是:name,年龄是{name}, 年龄是name,年龄是{age}岁”)

}

}

}



定义Mother印章类:

package cn.kotlin.kotlin_oop10

/**

  • 此类一

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享

旦被sealed修饰,就是印章类,此Mother类不能实例化了,只能实例化Mother.Man / WoMan

*/

sealed class Mother {

/**

  • MySealedPersonSex的>>> 类 男孩👱

*/

class Man(var name:String, var scale:Double) : Mother() {

/**

  • 打印姓名和重量的方法

*/

fun showNameAge() {

println(“这为男宝宝的 姓名是:name,重量是{name}, 重量是name,重量是{scale}岁”)

}

}

/**

  • MySealedPersonSex的>>> 类 女孩👩

*/

class WoMan(var name:String, var scale:Double) : Mother() {

/**

  • 打印姓名和重量的方法

*/

fun showNameAge() {

println(“这为女宝宝的 姓名是:name,年龄是{name}, 年龄是name,年龄是{scale}岁”)

}

}

}

main方法测试:

在这里插入图片描述

main方法测试:

package cn.kotlin.kotlin_oop10

fun main(args: Array) {

// 这样实例化Mother会报错,因为一旦被sealed修饰,就是印章类,此Mother类不能实例化了

// var mother = Mother()

/**

  • 必须是Mother定义的类

  • class Man() {}

*/

var mother1: Mother.Man = Mother.Man(“小华”, 7.80)

var mother2: Mother.Man = Mother.Man(“小俊”, 7.70)

var mother3: Mother.Man= Mother.Man(“小天”, 8.80)

var mother4: Mother.Man = Mother.Man(“天天”, 7.30)

var mother5: Mother.Man = Mother.Man(“小旺”, 7.10)

var mother6: Mother.Man = Mother.Man(“明旺”, 6.99)

/**

  • 必须是Mother定义的类

  • class WoMan() {}

*/

var mother7 = Mother.WoMan(“小美”, 8.20)

var mother8 = Mother.WoMan(“美美”, 7.12)

var mother9 = Mother.WoMan(“小芳”, 7.39)

var mother10 = Mother.WoMan(“小薇”, 8.00)

var mother11 = Mother.WoMan(“小苗”, 7.89)

var mother12 = Mother.WoMan(“柔柔”, 8.74)

var listMan = listOf<Mother.Man>(mother1,

mother2,

mother3,

mother4,

mother5,

mother6)

for (man in listMan) {

/**

  • man is Mother.Man is 判断这个man是不是等于/所属 Mother.Man

*/

if (man is Mother.Man)

man.showNameAge()

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐