什么是 class 常量?
What is a class constant?
我被告知声明并初始化我的 class 常量。我不知道它是什么所以我搜索了 google,显然每个人都已经知道它是什么并且没有人问过它。那么什么是 class 常数呢?它只是一个在整个 class 期间不会改变的值吗?
Class 变量是静态的;实例变量不是。
最终变量是常量。
所以一个 class 常量会这样声明:
public class Foo {
// Class constant
public static final String DEFAULT_NAME = "Bar";
public static void main(String [] args) {
String name = Foo.DEFAULT_NAME;
}
}
Foo
的所有实例都是一样的。
JLS-8.3.1.1. static
Fields 说(部分)
A static
field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).
JLS-4.12.4. final
Variables 说(部分)
A constant variable is a final
variable of primitive type or type String
that is initialized with a constant expression (§15.28)
tl;博士
将它们放在一起,一个 class 常量就是一个 static final
字段。
我被告知声明并初始化我的 class 常量。我不知道它是什么所以我搜索了 google,显然每个人都已经知道它是什么并且没有人问过它。那么什么是 class 常数呢?它只是一个在整个 class 期间不会改变的值吗?
Class 变量是静态的;实例变量不是。
最终变量是常量。
所以一个 class 常量会这样声明:
public class Foo {
// Class constant
public static final String DEFAULT_NAME = "Bar";
public static void main(String [] args) {
String name = Foo.DEFAULT_NAME;
}
}
Foo
的所有实例都是一样的。
JLS-8.3.1.1. static
Fields 说(部分)
A
static
field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).
JLS-4.12.4. final
Variables 说(部分)
A constant variable is a
final
variable of primitive type or typeString
that is initialized with a constant expression (§15.28)
tl;博士
将它们放在一起,一个 class 常量就是一个 static final
字段。