public class A
{
private static final int x;
public A()
{
x = 5;
}
}
Run Code Online (Sandbox Code Playgroud)
final 表示变量只能分配一次(在构造函数中).static 意味着它是一个类实例.我不明白为什么这是禁止的.这些关键字在哪里相互干扰?
我有一些代码:
final int var1;
if ( isSomethingTrue ) {
var1 = 123;
} else {
throwErrorMethod();
}
int var2 = var1;
Run Code Online (Sandbox Code Playgroud)
而throwErrorMethod的定义如下:
private void throwErrorMethod() throws Exception{
throw new Exception();
}
Run Code Online (Sandbox Code Playgroud)
我得到了声明的blank final field may not have been initialized编译错误var2 = var1.如果我内联方法,编译就好了!
throws Exception调用的方法?may会停止编译?!?java compiler-construction compiler-errors compiler-warnings
可能重复:
如何处理抛出已检查异常的静态最终字段初始值设定项
在这个例子中,我得到了错误的空白最后一个字段myClass的可能不被初始化:
private final static MyClass myClass; // <-- error
static {
try {
myClass = new MyClass(); // <-- throws exception
myClass.init();
} catch (Exception e) {
// log
}
}
Run Code Online (Sandbox Code Playgroud)
在那个例子中,我得到错误最终字段myClass可能已经被分配:
private final static MyClass myClass;
static {
try {
myClass = new MyClass(); // <-- throws exception
myClass.init();
} catch (Exception e) {
myClass = null; // <-- error
// log
}
}
Run Code Online (Sandbox Code Playgroud)
那个问题有什么解决方案吗?