在Java中,有什么区别:
private final static int NUMBER = 10;
和
private final int NUMBER = 10;
都是private
和final
,区别在于static
属性。
什么更好?为什么?
最佳答案
一般来说,static
的意思是“与类型本身相关联,而不是类型的实例。”
这意味着您可以引用静态变量而无需创建该类型的实例,并且引用该变量的任何代码都引用完全相同的数据。将此与实例变量进行比较:在这种情况下,类的每个实例都有一个独立版本的变量。比如:
Test x = new Test();
Test y = new Test();
x.instanceVariable = 10;
y.instanceVariable = 20;
System.out.println(x.instanceVariable);
打印出 10:y.instanceVariable
和 x.instanceVariable
是分开的,因为 x
和 y
指的是到不同的对象。
您可以通过引用来引用静态成员,尽管这样做是个坏主意。如果我们这样做了:
Test x = new Test();
Test y = new Test();
x.staticVariable = 10;
y.staticVariable = 20;
System.out.println(x.staticVariable);
然后会打印出 20 - 只有一个变量,而不是每个实例一个。写成这样会更清楚:
Test x = new Test();
Test y = new Test();
Test.staticVariable = 10;
Test.staticVariable = 20;
System.out.println(Test.staticVariable);
这使得行为更加明显。现代 IDE 通常会建议将第二个列表更改为第三个。
没有理由像下面那样使用内联声明来初始化值,因为每个实例都有自己的 NUMBER
但始终具有相同的值(不可变并使用文字进行初始化)。这与所有实例只有一个 final static
变量相同。
private final int NUMBER = 10;
因此,如果它不能改变,那么每个实例只有一个副本是没有意义的。
但是,如果在这样的构造函数中初始化是有意义的:
// No initialization when is declared
private final int number;
public MyClass(int n) {
// The variable can be assigned in the constructor, but then
// not modified later.
number = n;
}
现在,对于 MyClass
的每个实例,我们可以有一个不同但不可变的 number
值。
关于java - 私有(private)最终静态属性与私有(private)最终属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1415955/