美文网首页kotlin
30.init和次构造函数的执行顺序

30.init和次构造函数的执行顺序

作者: 写代码的向日葵 | 来源:发表于2019-10-01 23:57 被阅读0次
fun main(args: Array<String>) {
    val person = Person("张三", 12, "123456789012")
    
}
/**
 * 主构造函数
 */
class Person(var name: String, var age: Int) {

    var phone: String = ""
    constructor(name: String, age: Int, phone: String) : this(name, age) {
        this.phone = phone
        println("执行了次够函数")
    }

    init {
        println("执行了初始化")
    }
}

输出结果如下:


image.png
  • 无论调用主构造函数和次构造函数都会执行init
  • 调用次构造函数先执行init再执行次构造函数中的操作

相关文章

网友评论

    本文标题:30.init和次构造函数的执行顺序

    本文链接:https://www.haomeiwen.com/subject/zbjlpctx.html