open class BaseClass {
fun log(tag:String, s:String) {
println("$tag $s")
}
var mParam = ""
constructor() {
log("[base]", "constructor")
}
constructor(param:String) {
mParam = param
log("[base]", "constructor param $param")
}
fun createAValue(log:String):String {
println("create a value $log")
return "[base]"
}
init {
log("[base]", "init")
}
private val mValue1 = createAValue("【base】 mValue1 before init")
private val mValue2 = createAValue("【base】 mValue2 after init")
}
class SubClass : BaseClass {
constructor() {
log("[sub]", "constructor")
}
constructor(param: String) : super(param) {
log("[sub]","constructor param $param")
}
private val mValue1 = createAValue("【sub】 mValue1 before init")
init {
log("[sub]","init")
}
private val mValue2 = createAValue("【sub】 mValue2 after init")
}
fun main() {
println("------")
SubClass("aaaa")
println("------!!!")
}
kotlin
1. init{} 和全局变量的初始化,看谁写在前面
2. 构造函数永远最后走。
带父类的情况:
1. 先走父类的逻辑。即先(创建父类变量&init,按照代码顺序),然后父类构造函数
2. 再走子类的逻辑。先init{} 和全局变量的初始化,然后构造函数。
java:
也是先创建变量、再走构造函数。