String superInstanceStr = “I’m Super Instance Str1”;
static {
superStaticStr = “I’m Super Static Str2”;
}
static {
superStaticStr = “I’m Super Static Str3”;
}
public SuperInitVariable() {
superInstanceStr = “I’m Super Instance Str2”;
}
}
然后新建一个测试类:
package com.zwx.coreJava;
public class TestVariableOrder {
public static void main(String[] args) {
System.out.println(SuperInitVariable.superStaticStr);
SuperInitVariable superInitVariable = new SuperInitVariable();
System.out.println(superInitVariable.superInstanceStr);
}
}
输出结果:
I’m Super Static Str3
I’m Super Instance Str2
很明显,第一句话还没有实例化对象就可以输出静态变量,所以静态变量优先级最高,静态代码块也是一样会加载,多个代码块之间按先后顺序加载。
第二句成员变量先初始化了变量,再执行了构造器。所以可以得出如下结论:
-
1、静态变量优先级最先被初始化,多个静态代码块按代码先后顺序进行加载
-
2、成员变量先赋值,再执行构造函数
将上面的父类简单改造一下:
package com.zwx.coreJava;
public class SuperInitVariable {
static String superStaticStr = “I’m Super Static Str1”;
String superInstanceStr = “I’m Super Instance Str1”;
static {
superStaticStr = “I’m Super Static Str2”;
System.out.println(“Super Static:” + superStaticStr);
}
public SuperInitVariable() {
superInstanceStr = “I’m Super Instance Str2”;
System.out.println(“Super Construct:” + superStaticStr);
}
}
然后再新建一个子类,继承上面的SuperInitVariable:
package