如果在init中使用了成员变量,那么成员变量一定要定义在init之前,否则会爆Variable cannot be initialized before declaration 错误
不管调用哪个次级构造函数,都是先执行主构造函数(初始化成员变量和执行init代码块),再执行次级构造函数代码。所以kotlin规定次级构造函数先要委托给主构造函数。
成员变量初始化和init代码块谁先执行是按它们的声明顺序来的。
class InitTest {
private var num1 = 2
init {
num1 = 3
println("init方法:$num1")
}
init {
// num2 = 5
println("init方法2")
}
constructor() {
println("构造函数1")
}
constructor(params: String) {
println("构造函数2")
}
private var num2 = 4
}
public final class InitTest {
private int num1;
private int num2;
public InitTest() {
this.num1 = 2;
this.num1 = 3;
String var1 = "init方法:" + this.num1;
System.out.println(var1);
var1 = "init方法2";
System.out.println(var1);
this.num2 = 4;
var1 = "构造函数1";
System.out.println(var1);
}
public InitTest(@NotNull String params) {
Intrinsics.checkNotNullParameter(params, "params");
super();
this.num1 = 2;
this.num1 = 3;
String var2 = "init方法:" + this.num1;
System.out.println(var2);
var2 = "init方法2";
System.out.println(var2);
this.num2 = 4;
var2 = "构造函数2";
System.out.println(var2);
}
}
// InitTestKt.java
package com.lcf.study;
import kotlin.Metadata;
@Metadata(
mv = {1, 9, 0},
k = 2,
d1 = {"\u0000\b\n\u0000\n\u0002\u0010\u0002\n\u0000\u001a\u0006\u0010\u0000\u001a\u00020\u0001¨\u0006\u0002"},
d2 = {"main", "", "leetCodeJava"}
)
public final class InitTestKt {
public static final void main() {
new InitTest("222222222");
}
// $FF: synthetic method
public static void main(String[] var0) {
main();
}
}
网友评论