测试:

fun main() {
    val xiaoMing = Human("小明")
    xiaoMing.speak()
    
    var chenHaoNan = Human("陈浩南", "我陈浩南出来混,靠的就是三样东西:够狠、够义气、够朋友!")
    chenHaoNan.speak()
}

class Human (var name: String, var zuoyouming: String) { // 主构造函数
    constructor(name: String): this(name, "好好学习,天天向上") { // 辅助构造函数(secondary constructor)
        println("Human secondary constructor...")
//         this.name = name;
//         this.zuoyouming = zuoyouming;
    }
    
    init {
        println("Human init...")
    }
    
    fun speak() {
            println("我是$name, 我的座右铭是:$zuoyouming")
        }
}

打印:

ok.   可以看出int代码块比构造函数调用早。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐