对象属性的初始化有三种方式
故意把初始化块,放在构造方法下面,问题:
这三种方式,谁先执行?谁后执行

1
2
3
4
5
6
7
8
9
10
11
12
13
package charactor;

public class Hero {
public String name = "some hero";

public Hero(){
name = "one hero";
}
{
name = "the hero";
}

}

答案:
一 类 属性
二 静态代码块
三 代码块
四 构造方法代码块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Hero {
public String name =Hero.getName("属性声明") ;

public Hero(){
name = Hero.getName("构造方法");
}
{
name = Hero.getName("初始化块");
}

public static String getName(String pos){
String result= "name "+pos;
System.out.println(result);
return result;
}

public static void main(String[] args) {
new Hero();
}

}

运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class A {
public static int x;
static
{
x = B.y + 1;
}
{
int z=66666;
System.out.println(z);
}
}
public class B {
public static int y = A.x + 1;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(String.format("x=%d,y=%d",A.x, B.y));
new A();
}
}

图
按照以上执行顺序,先执行public static int y = A.x + 1;此时y=0,载入A,x=0+1=1,再回到y = A.x + 1,y=1+1=2
静态属性和静态代码块是按顺序执行,哪个在前面就先执行哪个,非静态变量和方法都是要new的