Java-可以在静态初始化块中初始化最终变量吗? [英] Java - Can final variables be initialized in static initialization block?
问题描述
根据我对Java语言的理解,可以在static initialization block
中初始化静态变量.
Based on my understanding of the Java language, static variables can be initialized in static initialization block
.
但是,当我尝试在实践中实现它(也是static
也是final
的变量)时,出现以下屏幕截图中所示的错误:
However, when I try to implement this in practice (static
variables that are final
too), I get the error shown in the screenshot below:
推荐答案
是的,当然:static final
变量可以在静态块中初始化,但是 ..您在其中具有隐式的GOTO.例子(try/catch
本质上是发生一些不好的事情时,GOTO捕获" ).
Yes of course: static final
variables can be initialized in a static block but.... you have implicit GOTOs in that example (try/catch
is essentially a 'GOTO catch if something bad happens').
如果引发异常,则您的final
变量将不会初始化.
If an exception is thrown your final
variables will not be initialized.
请注意,使用静态构造违反了面向对象的教条.这可能会使您的测试复杂化,并使调试更加困难.
Note that the use of static constructs goes against Object-Oriented dogma. It may complicate your testing and make debugging more difficult.
这篇关于Java-可以在静态初始化块中初始化最终变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!