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?
Say there is a test class:
You can access a static variable with it's class Name like this
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
Hope that explains your query.
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.
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.
Full example:
Instance variables:
The output will be:
Now, change the instance variable to a class variable by making it static:
Class variables:
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:
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.