java文档提到了这一点
static修饰符与final修饰符结合使用,也用于定义常量。
我只是想知道,可以使用final关键字来定义java中的常量。 我知道使用final关键字和没有static关键字声明的变量不能更改,但它是否算作常量?
The java documentation mentioned that
The static modifier, in combination with the final modifier, is also used to define constants.
I was just wondering, can the final keyword alone be used to define a constant in java. I know that variable declared with final keyword and without static keyword can't be changed, but does it count as a constant?
最满意答案
您需要static关键字来消除Class实例的上下文。 看一下下面的代码:
public class Main { public static final String CONST; static { if((System.currentTimeMillis() % 2) == 0) { CONST = "FOO"; } else { CONST = "BAR"; } } public final String CONST2; public Main(){ if((System.currentTimeMillis() % 2) == 0) { CONST2 = "FOO"; } else { CONST2 = "BAR"; } }}
虽然创建Main的多个实例将导致CONST2的值不同, 但是在加载类时将初始化CONST ,因此在Main的几个实例上保持相同。
更有趣的是,如果涉及多个ClassLoader ,您甚至可能拥有一个具有不同值的静态final变量。
因此,Java中的常量是使用常量值初始化的最终静态变量。
You need the static keyword to eliminate the context of the Class instance. Take a look at the following code:
public class Main { public static final String CONST; static { if((System.currentTimeMillis() % 2) == 0) { CONST = "FOO"; } else { CONST = "BAR"; } } public final String CONST2; public Main(){ if((System.currentTimeMillis() % 2) == 0) { CONST2 = "FOO"; } else { CONST2 = "BAR"; } }}
While creating multiple instances of Main will result in different values for CONST2, CONST will be initialized when the class is loaded and so stays the same over several instances of Main.
The more interesting is that you may even have a static final variable with different values in case that multiple ClassLoaders are involved.
So, a constant in Java is a final static variable that is initialized with a constant value.
更多推荐
发布评论