Java 私有最终静态属性与私有最终属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1415955/
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
private final static attribute vs private final attribute
提问by
In Java, what's the difference between:
在Java中,有什么区别:
private final static int NUMBER = 10;
and
和
private final int NUMBER = 10;
Both are private
and final
, the difference is the static
attribute.
都是private
和final
,区别在于static
属性。
What's better? And why?
什么更好?为什么?
回答by Martijn Courteaux
A static
variable stays in the memory for the entire lifetime of the application, and is initialised during class loading. A non-static
variable is being initialised each time you construct a new
object. It's generally better to use:
甲static
变量保持在该应用程序的整个生命周期的存储器,和类加载期间被初始化。static
每次构造new
对象时都会初始化一个非变量。通常最好使用:
private static final int NUMBER = 10;
Why? This reduces the memory footprint per instance. It possibly is also favourable for cache hits. And it just makes sense: static
should be used for things that are shared across all instances (a.k.a. objects) of a certain type (a.k.a. class
).
为什么?这减少了每个实例的内存占用。它也可能有利于缓存命中。它只是有道理:static
应该用于在某种类型(又名class
)的所有实例(又名对象)之间共享的事物。
回答by Jon Skeet
In general, static
means "associated with the typeitself, rather than an instanceof the type."
一般而言,static
表示“与类型本身相关联,而不是与类型的实例相关联”。
That means you can reference a static variable without having ever created an instances of the type, and any code referring to the variable is referring to the exact same data. Compare this with an instance variable: in that case, there's one independent version of the variable per instance of the class. So for example:
这意味着您可以引用静态变量而无需创建该类型的实例,并且引用该变量的任何代码都引用完全相同的数据。将其与实例变量进行比较:在这种情况下,类的每个实例都有一个独立版本的变量。例如:
Test x = new Test();
Test y = new Test();
x.instanceVariable = 10;
y.instanceVariable = 20;
System.out.println(x.instanceVariable);
prints out 10: y.instanceVariable
and x.instanceVariable
are separate, because x
and y
refer to different objects.
打印出 10: y.instanceVariable
andx.instanceVariable
是分开的,因为x
andy
指的是不同的对象。
You canrefer to static members via references, although it's a bad idea to do so. If we did:
您可以通过引用来引用静态成员,尽管这样做是个坏主意。如果我们这样做:
Test x = new Test();
Test y = new Test();
x.staticVariable = 10;
y.staticVariable = 20;
System.out.println(x.staticVariable);
then that would print out 20 - there's only one variable, not one per instance. It would have been clearer to write this as:
那么这将打印出 20 - 只有一个变量,而不是每个实例一个。把它写成这样会更清楚:
Test x = new Test();
Test y = new Test();
Test.staticVariable = 10;
Test.staticVariable = 20;
System.out.println(Test.staticVariable);
That makes the behaviour much more obvious. Modern IDEs will usually suggest changing the second listing into the third.
这使得行为更加明显。现代 IDE 通常会建议将第二个列表更改为第三个。
There is no reason to have an inline declaration initializing the value like the following, as each instance will have its own NUMBER
but always with the same value (is immutable and initialized with a literal). This is the same than to have only one final static
variable for all instances.
没有理由像下面那样使用内联声明来初始化值,因为每个实例都有自己的NUMBER
但始终具有相同的值(不可变并用文字初始化)。这与final static
所有实例只有一个变量相同。
private final int NUMBER = 10;
Therefore if it cannot change, there is no point having one copy per instance.
因此,如果它无法更改,则每个实例只有一个副本是没有意义的。
But, it makes sense if is initialized in a constructor like this:
但是,如果在这样的构造函数中初始化是有道理的:
// 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;
}
Now, for each instance of MyClass
, we can have a different but immutable value of number
.
现在,对于 的每个实例MyClass
,我们可以有一个不同但不可变的 值number
。
回答by duffymo
static means "associated with the class"; without it, the variable is associated with each instance of the class. If it's static, that means you'll have only one in memory; if not, you'll have one for each instance you create. static means the variable will remain in memory for as long as the class is loaded; without it, the variable can be gc'd when its instance is.
static 表示“与类相关联”;没有它,变量与类的每个实例相关联。如果它是静态的,那意味着你的内存中只有一个;如果没有,您创建的每个实例都会有一个。static 意味着只要加载了类,变量就会保留在内存中;没有它,当它的实例是变量时,它可以被 gc'd。
回答by DigitalRoss
very little, and static
很少,而且是静态的
There isn't much difference as they are both constants. For most class data objects, static would mean something associated with the class itself, there being only one copy no matter how many objects were created with new.
没有太大区别,因为它们都是常数。对于大多数类数据对象,静态意味着与类本身相关联的东西,无论用 new 创建了多少对象,都只有一个副本。
Since it is a constant, it may not actually be stored in either the class or in an instance, but the compiler still isn't going to let you access instance objects from a static method, even if it knows what they would be. The existence of the reflection API may also require some pointless work if you don't make it static.
由于它是一个常量,它实际上可能不会存储在类或实例中,但编译器仍然不会让您从静态方法访问实例对象,即使它知道它们将是什么。如果您不将其设为静态,反射 API 的存在也可能需要一些毫无意义的工作。
回答by Novitzky
As already Jon said, a static variable, also referred to as a class variable, is a variable which exists across instances of a class.
正如 Jon 已经说过的,静态变量,也称为类变量,是一个跨类实例存在的变量。
I found an example of this here:
我在这里找到了一个例子:
public class StaticVariable
{
static int noOfInstances;
StaticVariable()
{
noOfInstances++;
}
public static void main(String[] args)
{
StaticVariable sv1 = new StaticVariable();
System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);
StaticVariable sv2 = new StaticVariable();
System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);
System.out.println("No. of instances for st2 : " + sv2.noOfInstances);
StaticVariable sv3 = new StaticVariable();
System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);
System.out.println("No. of instances for sv2 : " + sv2.noOfInstances);
System.out.println("No. of instances for sv3 : " + sv3.noOfInstances);
}
}
Output of the program is given below:
程序的输出如下:
As we can see in this example each object has its own copy of class variable.
正如我们在这个例子中看到的,每个对象都有自己的类变量副本。
C:\java>java StaticVariable
No. of instances for sv1 : 1
No. of instances for sv1 : 2
No. of instances for st2 : 2
No. of instances for sv1 : 3
No. of instances for sv2 : 3
No. of instances for sv3 : 3
回答by Omar Al-Ithawi
The static one is the same member on all of the class instances and the class itself.
The non-static is one for every instance (object), so in your exact caseit's a waste of memory if you don'tput static.
静态成员是所有类实例和类本身的相同成员。
非静态是每个实例(对象)的一个,因此在您的确切情况下,如果您不放置静态,则会浪费内存。
回答by Sanjay
If you mark this variable static then as you know, you would be requiring static methods to again access these values,this will be useful if you already think of using these variables only in static methods. If this is so then this would be the best one.
如果您将此变量标记为静态,那么正如您所知,您将需要静态方法来再次访问这些值,如果您已经考虑仅在静态方法中使用这些变量,这将非常有用。如果是这样,那么这将是最好的。
You can however make the variable now as public since no one can modify it just like "System.out", it again depends upon your intentions and what you want to achieve.
但是,您现在可以将变量设为公开,因为没有人可以像“System.out”那样修改它,这又取决于您的意图和想要实现的目标。
回答by Anonymous
From the tests i have made, static final variables are not the same with final(non-static) variables! Final(non-static) variables can differ from object to object!!! But that's only if the initialization is made within the constructor! (If it is not initialized from the constructor then it is only a waste of memory as it creates final variables for every object that is created that cannot be altered.)
从我所做的测试来看,静态最终变量与最终(非静态)变量不同!最终(非静态)变量可能因对象而异!!!但这仅当在构造函数中进行初始化时!(如果它不是从构造函数初始化,那么它只是浪费内存,因为它为每个创建的对象创建了无法更改的最终变量。)
For example:
例如:
class A
{
final int f;
static final int sf = 5;
A(int num)
{
this.f = num;
}
void show()
{
System.out.printf("About Object: %s\n Final: %d\n Static Final: %d\n\n", this.toString(), this.f, sf);
}
public static void main(String[] args)
{
A ob1 = new A(14);
ob1.show();
A ob2 = new A(21);
ob2.show();
}
}
What shows up on screen is:
屏幕上显示的是:
About Object: A@addbf1 Final: 14 Static Final: 5
关于对象:A@addbf1 决赛:14 静态决赛:5
About Object: A@530daa Final: 21 Static Final: 5
关于对象:A@530daa 决赛:21 静态决赛:5
Anonymous 1st year IT student, Greece
匿名 1 年级 IT 学生,希腊
回答by rommel
Lets say if the class will not have more than one instance ever, then which one takes more memory:
假设该类永远不会有多个实例,那么哪一个需要更多内存:
private static final int ID = 250; or private final int ID = 250;
私有静态最终整数 ID = 250;或私有最终 int ID = 250;
I've understood that static will refer to the class type with only one copy in the memory and non static will be in a new memory location for each instance variable. However internally if we just compare 1 instance of the same class ever (i.e. more than 1 instance would not be created), then is there any overhead in terms of space used by 1 static final variable?
我已经理解静态将指代在内存中只有一个副本的类类型,非静态将在每个实例变量的新内存位置中。但是在内部,如果我们只是比较同一类的 1 个实例(即不会创建 1 个以上的实例),那么在 1 个静态最终变量使用的空间方面是否有任何开销?
回答by lucas
For final, it can be assigned different values at runtime when initialized. For example
对于final,它可以在初始化时在运行时分配不同的值。例如
Class Test{
public final int a;
}
Test t1 = new Test();
t1.a = 10;
Test t2 = new Test();
t2.a = 20; //fixed
Thus each instance has different value of field a.
因此,每个实例都有不同的字段a值。
For static final, all instances share the same value, and can't be altered after first initialized.
对于static final,所有实例共享相同的值,并且在第一次初始化后不能更改。
Class TestStatic{
public static final int a;
}
TestStatic t1 = new TestStatic();
t1.a = 10;
TestStatic t2 = new TestStatic();
t1.a = 20; // ERROR, CAN'T BE ALTERED AFTER THE FIRST INITIALIZATION.