public class Elvis {
public static final Elvis ELVIS = new Elvis();
private Elvis() {}
private static final Boolean LIVING = true;
private final Boolean alive = LIVING;
public final Boolean lives() {
return alive;
}
public static void main(String[] args) {
System.out.println(ELVIS.lives() ? "Hound Dog" : "Heartbreak Hotel");
}
}
运行结果为:
Exception in thread "main" java.lang.NullPointerException
抛出异常的原因是创建LIVING属性在创建ELVIS之后,调用方式时LIVING还没有被创建
正确的代码为:
public class Elvis {
private static final Boolean LIVING = true;
public static final Elvis ELVIS = new Elvis();
private Elvis() {}
private final Boolean alive = LIVING;
public final Boolean lives() {
return alive;
}
public static void main(String[] args) {
System.out.println(ELVIS.lives() ? "Hound Dog" : "Heartbreak Hotel");
}
}