Java-可以在静态初始化块中初始化最终变量吗? [英] Java - Can final variables be initialized in static initialization block?

查看:109
本文介绍了Java-可以在静态初始化块中初始化最终变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我对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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆