gpt4 book ai didi

java - 如何从Java中的其他类初始化静态最终变量

转载 作者:行者123 更新时间:2023-12-01 18:48:24 25 4
gpt4 key购买 nike

I want to initialize Final.value in Main method. 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;


}

最佳答案

你不能。您可能认为 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 之前还发生了其他事情。

使该字段成为最终字段并不会改变这一事实。

<小时/>

静态初始化有两种选择。在静态初始化 block 中,如您所示,或内联:

static final int value = 421

Java 阻止你做你想做的事情是有充分理由的:因为它可能会导致错误。

关于java - 如何从Java中的其他类初始化静态最终变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59776216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com