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

相关推荐
年小个大9 小时前
受 go-zero 启发,我给 Flutter 写了一套 CLI 脚手架
android·flutter·架构
Android-Flutter10 小时前
为什么说ActivityThread是主线程?
android·kotlin
余额瞒着我当琳12 小时前
C++模板初阶与STL初探
android·java·c++
知行合一。。。14 小时前
DeepAgents--01--Agent和OpenClaw的相关概念
android·数据库
汪海游龙16 小时前
告别 Play Console 手动上传:从模拟器截图到自动发版的完整流水线
android·ci/cd·github
weixin_4407841116 小时前
【IntentSeivice实现原理】
android·java·开发语言·intentservice
delta_hell16 小时前
【阅读源码--Android】动画之ValueAnimator--2
android·源码·valueanimator
delta_hell16 小时前
【阅读源码--Android】动画之辅助类
android·源码·animator
学习使我健康16 小时前
一个基于 **Jetpack Compose + Material 3** 的 Android 入门示例项目,演示 Compose 声明式 UI 的核心用法
ui·kotlin·android jetpack
delta_hell19 小时前
【阅读源码--Android】动画之ValueAnimator--1
android·源码·valueanimator