Static vs Instance Variables: Difference?

谁说我不能喝 提交于 2019-11-26 04:23:36

问题


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?


回答1:


In the context of class attributes, static has a different meaning. If you have a field like:

private static int sharedAttribute;

then, each and every instance of the class will share the same variable, 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:

  1. 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 lot of instances of that class. Not sure about concurrent access, though.
  2. variables that are intended to be shared, such as reference counters &co.

static vars are instantiated before your program starts, so if you have too many of them, you could slow down startup.

A static method can only access static attributes, but think twice before trying this.

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.




回答2:


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

 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.




回答3:


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

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:

987654
987654




回答4:


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.




回答5:


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.




回答6:


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.




回答7:


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




回答8:


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:

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.
     }
}



回答9:


Consider a class MyClass, having one static and one non-static member:

public class MyClass {
    public static int STATICVARIABLE = 0;
    public int nonStaticVariable = 0;
}

Now, let's create a main() to create a couple of instances:

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.



来源:https://stackoverflow.com/questions/21204589/static-vs-instance-variables-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!