-
Kotlin的枚举,重点区分的数据本身
-
Kotlin的印章类,重点区分的是数据类型(类)
枚举类的定义:
package cn.kotlin.kotlin_oop09
/**
- 定义人的性别 枚举类
*/
enum class MyEnumPersonSex {
男, 女
}
印章类的定义:
package cn.kotlin.kotlin_oop10
/**
- 此类一旦被sealed修饰,就是印章类,此类不能实例化了,只能实例化MySealedPersonSex.Man / WoMan
*/
sealed class MySealedPersonSex {
/**
- MySealedPersonSex的>>> 类 男人👱
*/
class Man(var name:String, var age:Int) {
/**
- 打印姓名和年龄的方法
*/
fun showNameAge() {
println(“这为男人的 姓名是: n a m e , 年龄是 {name}, 年龄是 name,年龄是{age}岁”)
}
}
/**
- MySealedPersonSex的>>> 类 女人👩
*/
class WoMan(var name:String, var age:Int) {
/**
- 打印姓名和年龄的方法
*/
fun showNameAge() {
println(“这为女人的 姓名是: n a m e , 年龄是 {name}, 年龄是 name,年龄是{age}岁”)
}
}
}
定义Mother印章类:
package cn.kotlin.kotlin_oop10
/**
- 此类一旦被sealed修饰,就是印章类,此Mother类不能实例化了,只能实例化Mother.Man / WoMan
*/
sealed class Mother {
/**
- MySealedPersonSex的>>> 类 男孩👱
*/
class Man(var name:String, var scale:Double) : Mother() {
/**
- 打印姓名和重量的方法
*/
fun showNameAge() {
println(“这为男宝宝的 姓名是: n a m e , 重量是 {name}, 重量是 name,重量是{scale}岁”)
}
}
/**
- MySealedPersonSex的>>> 类 女孩👩
*/
class WoMan(var name:String, var scale:Double) : Mother() {
/**
- 打印姓名和重量的方法
*/
fun showNameAge() {
println(“这为女宝宝的 姓名是: n a m e , 年龄是 {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)