java 什么是类常量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33663741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:57:44  来源:igfitidea点击:

What is a class constant?

javaclassconstantsterminology

提问by Kyle

I am told to declare and initialize my class constant. I didn't know what it was so I searched google, apparently everyone already knows what it is and nobody has asked on it. So what is a class constant? Is it just a value that doesn't change throughout the class?

我被告知要声明并初始化我的类常量。我不知道它是什么所以我搜索了谷歌,显然每个人都已经知道它是什么并且没有人问过它。那么什么是类常量呢?它只是一个在整个类中都不会改变的值吗?

采纳答案by Elliott Frisch

JLS-8.3.1.1. staticFieldssays (in part)

JLS-8.3.1.1。static字段说(部分)

A staticfield, sometimes called a class variable, is incarnated when the class is initialized (§12.4).

一个static字段,有时也称为类变量,在类被初始化时体现出来(第12.4 节)。

JLS-4.12.4. finalVariablessays (in part)

JLS-4.12.4。final变量说(部分)

A constant variableis a finalvariable of primitive type or type Stringthat is initialized with a constant expression (§15.28)

常量变量final原始类型或类型的变量String,其与一个常量表达式初始化(§15.28

tl;dr

tl;博士

Putting that together, a class constant is a static finalfield.

综上所述,类常量就是一个static final字段。

回答by duffymo

Class variables are static; instance variables are not.

类变量是静态的;实例变量不是。

Final variables are constant.

最终变量是常数。

So a class constant would be declared like this:

所以一个类常量会像这样声明:

public class Foo {

    // Class constant 
    public static final String DEFAULT_NAME = "Bar";

    public static void main(String [] args) {
        String name = Foo.DEFAULT_NAME;
    }
}

It's the same for all instances of Foo.

的所有实例都是一样的Foo