我想在Main方法中初始化Final.value。是否可以在其他类中初始化静态最终常量在其减速舱中?
public class Main {
public static void main(String[] args) {
//I want to initialize Final.value in Main method.
}
}
class Final {
//here is the static final variable which can be assigned vai a static block
//but how do I initialize it in the main method if I don't use the static block?
static final int value;
}
您不能。您的感觉可能是main
早于其他所有事物,因此可以安全地在此处进行初始化,但这是不正确的。
请考虑以下代码。
class Scratch
{
static
{
System.out.println(Foo.i);
}
public static void main(String[] args)
{
Foo.i = 100;
}
}
class Foo
{
static int i;
}
它不会打印100。它会打印0,因为在main
之前还有其他事情发生。
将字段定为决赛不会改变这一事实。
您有两个用于静态初始化的选项。在静态初始化程序块中,如您所显示的那样,或在线进行:
static final int value = 421
Java有充分的理由阻止您执行想要做的事情:因为它可能会导致错误。