成員變量的初始化
- 在變量聲明出初始化
- 使用初始化塊初始化
- 使用構造器初始化
初始化執行順序
- 聲明處初始化和初始化塊執行早於構造器
- 聲明處初始化和初始化塊按照代碼的順序執行,先聲明的先執行
public class Init {
//變量聲明處初始化
int age = f();
//初始化塊初始化
{
System.out.println("初始化塊執行");
age=10;
}
//構造器初始化
public Init(){
age =10;
System.out.println("構造器執行");
}
public int f(){
System.out.println("聲明處初始化");
return 3;
}
public static void main(String[] args) {
Init in = new Init();
}
}
創建對象,成員變量先分配空間,變量的值爲成員變量的默認值,分配空間完成後才進行初始化。
public class Init2 {
{
System.out.println("age ="+this.age);
}
int age = f();
int a = 100;
public int f(){
System.out.println("a的值:"+a);
return 3;
}
public static void main(String[] args) {
Init2 in = new Init2();
}
}
//age =0
//a的值:0