JAVA实例变量的初始化过程

假设有这样一段代码:

public class Cat {



private String name;
private int age;


public String toString() {
return "Cat [name=" + name + ", age=" + age + ", weight=" + weight
+ "]";
}


public Cat(String name, int age) {
System.out.println("Cat构造函数开始执行");
this.name = name;
this.age = age;
}


{
System.out.println("非静态代码块开始执行");
 weight=2.0;
}
private double weight = 2.8;

}

public class Tets02 {


/**
* @param args
*/
public static void main(String[] args) {
Cat cat= new Cat("波斯猫",2);
System.out.println(cat.toString());
}


}

得出来weight的值是2.8;

执行的过程是:

double weight;

weight=2.0//非静态代码块执行

weight=2.8

此时weight=2.8是发生在构造函数中的。

但是如果是:

public class Cat {


private String name;
private int age;
private double weight = 2.8;
public String toString() {
return "Cat [name=" + name + ", age=" + age + ", weight=" + weight
+ "]";
}


public Cat(String name, int age) {
System.out.println("Cat构造函数开始执行");
this.name = name;
this.age = age;
}


{
System.out.println("非静态代码块开始执行");
 weight=2.0;
}

}

得到的结果是weight=2.0

说明初始化代码块与构造函数的地位平等,完全是按照代码先后来执行的

 

你可能感兴趣的:(java)