Kotlin:为什么创建类不能被继承

一、为什么创建类不能被继承

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文件代码

bash 复制代码
abstract class Car {
    private var mPrice: String? = null

    fun 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:类、构造函数、继承

相关推荐
千里马学框架4 天前
一起学 Android 14:ShellTransition 屏幕旋转过程深度剖析
android·智能手机·性能优化·framework·性能·屏幕旋转·rotation
美狐美颜SDK开放平台4 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
AFinalStone4 天前
Android7 SystemUI源码解析(七)Keyguard锁屏模块深度解析
android·systemui
致远ccc4 天前
Google Play 上架前如何测试 App?多国家 Android 环境测试
android·app测试·googleplay·多国家应用测试
ttyyttemo4 天前
Kotlin 协程中的 Job 结构化并发与取消
android
sun0077004 天前
tbox 4g/5g切换,导致wan ip 改变,导致车机旧网络不可用。需要重启车机才行
android
ai2work4 天前
ch23 综合复刻:从零做一个最小可用版本(capstone)
kotlin
其实防守也摸鱼4 天前
内网穿透与反向代理:原理、工具与实战指南
android·大数据·运维·安全·网络安全·自动化·渗透
ai2work4 天前
ch21 签名、校验与发版
kotlin
AFinalStone5 天前
Android7 SystemUI 源码解析(四)NavigationBar 导航栏与 SystemBars
android·systemui