序言
很多人用java,但是又有多少人真的懂java,我就是对java不是很懂的那部分,还记得有次笔试题让我写代码执行顺序,当时一脸蒙,平时谁有去关心代码执行顺序的啊,只会觉得感觉是这样,写出的代码也没问题就对了。这个就大错特错了,下面还是用demo看下执行顺序吧!
上代码:
public class Insect {
private int i=9;
protected int j;
Insect(){
System.out.println("i="+i+",j="+j);
j=39;
}
static {
Insect.printInt("Insect static code");
}
private static int x1 = printInt("static Insect.x1 initialized");
static int printInt(String s){
System.out.println(s);
return 47;
}
}
public class Beetle extends Insect {
private int k = printInt("Beetle.k initialized");
public Beetle(){
System.out.println("k="+k);
System.out.println("j="+j);
}
private static int x2 = printInt("static Beetle.x2 initialized");
public static void main(String[] args) {
System.out.println("Beetle constructor");
Beetle b = new Beetle();
}
static {
Insect.printInt("Beetle static code");
}
}
执行结果:
结论:
1.先静态再非静态
2.先父类再之类
3.先属性再构造
4.同级代码块自上而下