Java 静态变量与实例变量:区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21204589/
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
Static vs Instance Variables: Difference?
提问by
What is the difference between a static and instance variable. The following sentence is what I cant get:
静态变量和实例变量有什么区别。以下句子是我无法理解的:
In certain cases, only one copy of a particular variable should be shared by all objects of a class- here a static variable is used.
A static variable represents class wide info.All objects of a class share the same data.
在某些情况下,一个类的所有对象应该只共享一个特定变量的一个副本——这里使用的是静态变量。
静态变量代表类范围的信息。类的所有对象共享相同的数据。
I thought that instance vars were used class wide whereas static variables only had scope within their own methods?
我认为实例变量在类范围内使用,而静态变量只在它们自己的方法内有作用域?
采纳答案by Stefano Sanfilippo
In the context of class attributes, static
has a different meaning. If you have a field like:
在类属性的上下文中,static
具有不同的含义。如果您有一个字段,例如:
private static int sharedAttribute;
then, each and every instanceof the class will share the samevariable, so that if you change it in one instance, the change will reflect in all instances, created either before or after the change.
然后,类的每个实例都将共享相同的变量,因此如果您在一个实例中更改它,则更改将反映在更改之前或之后创建的所有实例中。
Thus said, you might understand that this is bad in many cases, because it can easiy turn into an undesired side-effect: changing object a
also affects b
and you might end up wondering why b
changed with no apparent reasons. Anyway, there are cases where this behaviour is absolutely desirable:
如此说来,您可能会理解这在许多情况下是不好的,因为它很容易变成不想要的副作用:更改对象a
也会产生影响b
,您最终可能想知道为什么b
在没有明显原因的情况下更改。无论如何,在某些情况下,这种行为是绝对可取的:
- class constants: since they are
const
, having all the classes access the same value will do no harm, because no one can change that. They can save memory too, if you have a lotof instances of that class. Not sure about concurrentaccess, though. - variables that are intendedto be shared, such as reference counters &co.
- 类常量:因为它们是
const
,所以让所有类访问相同的值不会有什么坏处,因为没有人可以改变这一点。如果您有很多该类的实例,它们也可以节省内存。不过,不确定并发访问。 - 旨在共享的变量,例如引用计数器 &co。
static
vars are instantiated before your program starts, so if you have too many of them, you couldslow down startup.
static
vars 在你的程序启动之前被实例化,所以如果你有太多的变量,你可能会减慢启动速度。
A static
method can only access static
attributes, but think twice before trying this.
一个static
方法只能访问static
属性,但在尝试之前要三思。
Rule of thumb: don't use static
, unless it is necessary and you know what you are doing or you are declaring a class constant.
经验法则:不要使用static
,除非有必要并且你知道你在做什么或者你正在声明一个类常量。
回答by avak
I think you are thinking about the C/C++ definition of the static keyword. There, the static keyword has many uses. In Java, the static keyword's functionality is described in your post. Anyhow, you can try it for yourself:
我认为您正在考虑 static 关键字的 C/C++ 定义。在那里,static 关键字有很多用途。在 Java 中,您的帖子中描述了 static 关键字的功能。无论如何,您可以自己尝试一下:
public class Test_Static{
static int x;
public static void main(String[] argv){
Test_Static a = new Test_Static();
Test_Static b = new Test_Static();
a.x = 1; // This will give an error, but still compile.
b.x = 2;
System.out.println(a.x); // Should print 2
}
}
and similarly for non static variables:
和非静态变量类似:
public class Test_NonStatic{
int x;
public static void main(String [] argv){
Test_NonStatic a = new Test_NonStatic();
Test_NonStatic b = new Test_NonStatic();
a.x = 1;
b.x = 2;
System.out.println(a.x); // Should print 1.
}
}
回答by avak
Say there is a test class:
假设有一个测试类:
class Test{
public static int a = 5;
public int b = 10;
}
// here t1 and t2 will have a separate copy of b
// while they will have same copy of a.
Test t1 = new test();
Test t2 = new test();
You can access a static variable with it's class Name like this
您可以像这样使用类名称访问静态变量
Test.a = 1//some value But you can not access instance variable like this
System.out.println(t1.a);
System.out.println(t2.a);
In both cases output will be 1 as a is share by all instances of the test class. while the instance variable will each have separate copy of b (instance variable) So
在这两种情况下,输出都是 1,因为测试类的所有实例都共享。而实例变量将每个都有单独的 b(实例变量)副本所以
t1.b = 15 // will not be reflected in t2.
System.out.println(t1.b); // this will print 15
System.out.println(t2.b); / this will still print 10;
Hope that explains your query.
希望能解释您的查询。
回答by jeswin
Class variables only have one copy that is shared by all the different objects of a class, whereas every object has it's own personal copy of an instance variable. So, instance variables across different objects can have different values whereas class variables across different objects can have only one value.
类变量只有一个副本,由一个类的所有不同对象共享,而每个对象都有自己的实例变量的个人副本。因此,跨不同对象的实例变量可以具有不同的值,而跨不同对象的类变量只能具有一个值。
回答by Venkat Bramhaiah
Static(Class) variables and instance variables both are member variables because they are both associated with a specific class, but the difference between them is Class variables only have one copy that is shared by all the different objects of a class, whereas every object has it's own personal copy of an instance variable. So, instance variables across different objects can have different values whereas class variables across different objects can have only one value.
静态(类)变量和实例变量都是成员变量,因为它们都与特定的类相关联,但它们之间的区别是类变量只有一个副本,由一个类的所有不同对象共享,而每个对象都有它是实例变量的个人副本。因此,跨不同对象的实例变量可以具有不同的值,而跨不同对象的类变量只能具有一个值。
回答by Yel
Instance Variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Static Variable would only be one copy of each class variable per class, regardless of how many objects are created from it.
实例变量包含必须由多个方法、构造函数或块引用的值,或者必须存在于整个类中的对象状态的基本部分。静态变量对于每个类的每个类变量只会是一个副本,无论从中创建了多少对象。
回答by Suchi Gupta
Instance variables:
实例变量:
These variables belong to the instance of a class, thus an object. And every instance of that class (object) has it's own copy of that variable. Changes made to the variable don't reflect in other instances of that class.
这些变量属于一个类的实例,因此是一个对象。并且该类(对象)的每个实例都有它自己的该变量的副本。对变量所做的更改不会反映在该类的其他实例中。
public class Product {
public int barcode;
}
Class variables:
类变量:
These are also known as static member variables and there's only one copy of that variable that is shared with all instances of that class. If changes are made to that variable, all other instances will see the effect of the changes.
这些也称为静态成员变量,并且只有该变量的一个副本与该类的所有实例共享。如果对该变量进行了更改,则所有其他实例都会看到更改的效果。
public class Product {
public static int barcode;
}
Full example:
完整示例:
Instance variables:
实例变量:
public class Main {
public static void main(String[] args) {
Product prod1 = new Product();
prod1.barcode = 123456;
Product prod2 = new Product();
prod2.barcode = 987654;
System.out.println(prod1.barcode);
System.out.println(prod2.barcode);
}
}
public class Product {
public int barcode;
}
The output will be:
输出将是:
123456
987654
123456
987654
Now, change the instance variable to a class variable by making it static:
现在,将实例变量设置为静态,将其更改为类变量:
Class variables:
类变量:
public class Main {
public static void main(String[] args) {
Product prod1 = new Product();
prod1.setBarcode(123456);
Product prod2 = new Product();
prod2.setBarcode(987654);
System.out.println(prod1.getBarcode());
System.out.println(prod2.getBarcode());
}
}
public class Product {
public static int barcode;
public int getBarcode() {
return barcode;
}
public void setBarcode(int value){
barcode = value;
}
}
I used non-static methods to get and set the value of Barcode to be able to call it from the object and not from the class.
The output will be following:
我使用非静态方法来获取和设置 Barcode 的值,以便能够从对象而不是从类中调用它。
输出如下:
987654
987654
987654
987654
回答by user3729220
Consider a class MyClass
, having one static and one non-static member:
考虑一个MyClass
具有一个静态成员和一个非静态成员的类:
public class MyClass {
public static int STATICVARIABLE = 0;
public int nonStaticVariable = 0;
}
Now, let's create a main()
to create a couple of instances:
现在,让我们创建一个main()
来创建几个实例:
public class AnotherClass{
public static void main(String[] args) {
// Create two instances of MyClass
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.nonStaticVariable = 30; // Setting value for nonstatic varibale
obj1.STATICVARIABLE = 40; //Setting value for static variable
obj2.nonStaticVariable = 50;
obj2.STATICVARIABLE = 60;
// Print the values actually set for static and non-static variables.
System.out.println(obj1.STATICVARIABLE);
System.out.println(obj1.nonStaticVariable);
System.out.println(obj2.STATICVARIABLE);
System.out.println(obj2.nonStaticVariable);
}
}
Result:
结果:
60
30
60
50
Now you can see value of the static variable printed 60
both the times, as both obj1
and obj2
were referring to the same variable. With the non-static variable, the outputs differ, as each object when created keeps its own copy of non-static variable; changes made to them do not impact on the other copy of the variable created by another object.
现在你可以看到打印的静态变量的值,60
这两个时间,因为两者obj1
并obj2
分别指的是同一个变量。对于非静态变量,输出不同,因为每个对象在创建时都保留自己的非静态变量副本;对它们所做的更改不会影响由另一个对象创建的变量的另一个副本。
回答by sachin
Suppose we create a static variable K and in the main function we create three objects: ob1 ob2 ob3; All these objects can have the same value for variable K. In contrast if the variable K was an instance variable then it could have different values as: ob1.k ob2.k ob3.k
假设我们创建了一个静态变量 K 并且在主函数中我们创建了三个对象:ob1 ob2 ob3;所有这些对象对于变量 K 可以具有相同的值。相反,如果变量 K 是一个实例变量,那么它可以具有不同的值: ob1.k ob2.k ob3.k