可以使用final关键字来定义java中的常量(can the final keyword alone be used to define a constant in java)

编程入门 行业动态 更新时间:2024-10-27 23:26:49
可以使用final关键字来定义java中的常量(can the final keyword alone be used to define a constant in java)

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.

更多推荐

本文发布于:2023-04-28 15:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1332442.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常量   可以使用   关键字   定义   final

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!