kotlin 类继承的语法

写段测试代码:

Kotlin 复制代码
open class Person { // 加open关键字,可以被子类继承
    open var name: String = ""
    open var age: Int = 0
    
    constructor(name: String, age: Int) {
        this.name = name
        this.age = age
    }
    
    override fun toString() : String {
        return "我是${name}, 年龄$age." //这里不能写this.name, this.age,不然会栈溢出。为啥??
    }
}

class Daxia : Person {
    var kongfus: List<String> = listOf()
    var wuli: Int = 0
    
    constructor(name: String, age: Int, kongfus: List<String>, wuli: Int) : super(name, age) {
        this.kongfus = kongfus
        this.wuli = wuli
    }
    
    override fun toString() : String {
        return super.toString() + "我会的武功:${kongfus}, 我的武力值: $wuli"
    }
}

fun main() {    
    val zhouzhiruo =  Daxia("周芷若", 23, listOf("九阴真经"), 89)
    val tianboguang = Daxia("田伯光", 30, listOf("狂风刀法"), 81)
    val duanzhengchun = Daxia("段正淳", 42, listOf("一阳指"), 80)
    val jiumozhi = Daxia("鸠摩智", 40, listOf("小无相功", "少林七十二绝技", "少林易筋经", "火焰刀"), 96)
    
    println(zhouzhiruo.toString())
    println(tianboguang.toString())
    println(duanzhengchun.toString())
    println(jiumozhi.toString())
}

打印:

ok.

相关推荐
Kapaseker1 天前
一杯美式搞定 Kotlin 空安全
android·kotlin
FunnySaltyFish2 天前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
Kapaseker2 天前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
Kapaseker3 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
A0微声z5 天前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
alexhilton5 天前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
lhDream6 天前
Kotlin 开发者必看!JetBrains 开源 LLM 框架 Koog 快速上手指南(含示例)
kotlin
RdoZam6 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
Kapaseker6 天前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin
郑州光合科技余经理7 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php