一、为什么创建类不能被继承
class或data class 默认情况下,Kotlin 类是最终(final)的:它们不能被继承。
示例:data class PsersonBean
反编译data class PsersonBean 生成 public final class PsersonBean
示例:class User
反编译class User生成** public final class User**
二、让类可继承的方式有几种
1. 用 open 关键字标记类
示例:open class Shape
继承示例:class Circle() : Shape()
2. 用abstract将类声明为抽象类
示例:abstract class Car
Testabstract.kt文件代码
abstract class Car {private var mPrice: String? = nullfun setPrice(price: String?) {mPrice = price}fun getPrice(): String {return mPrice ?: "0.00"}}class M9SUVCar : Car() {
}class U8SUVCar : Car() {
}fun main() {val m9Car = M9SUVCar()m9Car.setPrice("46.80")val u8SUVCar = U8SUVCar()u8SUVCar.setPrice("109.80")println("M9SUVCar的价格:${m9Car.getPrice()} 万元")println("U8SUVCar的价格:${u8SUVCar.getPrice()} 万元")
}
运行结果
推荐
Kotlin:类、构造函数、继承