Class variables

Class variables are fields in a class that are declared as static which means that it belongs to the particular class, not any objects that are instantiated from that class.
It also means that the value of the class variable is the same in every object created from that class.
A class variable can have one and only one value no matter how many objects that are created from it.

The example below shows a class variable of type int. Two objects are created from the VariableExample class.
First the value of the class variable is printed out for both objecs which shows the same value.
Then it’s value is altered using the class name and printed out again for both instances, and the value has changed for both.
As a final test the value is altered for one of the object instances only, and then the values for both objects are printed out yet another time.
Again it show the same value for both instances.
This shows that if a class variable is changed in one object, it gets changed for every object of that type since class instance variables holds only one value despite the number of instantiated objects.

The output from the code above is:

Search for more Java info on this site here:
Custom Search

Please type any questions here.