[英]how to initialize static final variable from other class in java
I want to initialize Final.value in Main method.
我想在 Main 方法中初始化 Final.value。 Is it possible to initialize static final constant in other class than in its deceleration class?
是否可以在其他类中而不是在其减速类中初始化静态最终常量?
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;
}
You cannot.你不能。 Your perception might be that
main
happens before everything else, so it is safe to initialise things there, but that is incorrect.您的看法可能是
main
发生在其他一切之前,因此在那里初始化事物是安全的,但这是不正确的。
Consider the following code.考虑以下代码。
class Scratch
{
static
{
System.out.println(Foo.i);
}
public static void main(String[] args)
{
Foo.i = 100;
}
}
class Foo
{
static int i;
}
It does not print 100. It prints 0 because there are other things which happen before main
.它不打印 100。它打印 0 因为在
main
之前发生了其他事情。
Making the field final does not change that fact.将字段设为 final 并不会改变这一事实。
You have two options for static initialization.您有两种静态初始化选项。 In a static initializer block, like you showed, or in-line:
在静态初始化程序块中,如您所示,或内嵌:
static final int value = 421
Java prevents you from doing what you want to do for a good reason: because it is likely to lead to bugs. Java 阻止您做您想做的事情是有充分理由的:因为它可能会导致错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.