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

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

问题描述

根据我对Java语言的理解,可以在静态初始化块中初始化静态变量.

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 catch').

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天全站免登陆