public class Elvis {
public static final Elvis INSTANCE = new Elvis();
private final int beltSize;
private static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR); // 0,正确的结果应该是:2022
private Elvis() {
beltSize = CURRENT_YEAR - 1930; // static final 类型静态域被初始化之前可能被读取,读到的结果是0,本应该是当前年份
}
public int beltSize() {
return beltSize;
}
public static void main(String[] args) {
System.out.println("Elvis wears a size " + INSTANCE.beltSize() + " belt.");
}
}
问题现原因:INSTANCE在CURRENT_YEAR之前被初始化了。
解决方法:
private static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR); // 0,解决方法:CURRENT_YEAR放到上面去
public static final Elvis INSTANCE = new Elvis();
调整初始化顺序,让被依赖的项优先初始化。