Class Variables
by , 04-26-2012 at 04:44 PM (218 Views)
When objects are made from the similar class blue print it means that every one of them consist of their distinct instance variables copies. In Bicycle class case, instance variables are speed, gear and cadence. E very Bicycle object consist of values of its own, for these variables which are present at different locations of memory.
Sometimes one wishes to possess variables which are common, to all objects. This is usually done by the static modifier. Fields which consist of static modifier in declaration are known as class variables or static fields. Usually they are linked to the class instead of any object. Each instance shares the class variable that is present in just one location of the memory. Class variable’s value could be changed by any object however manipulation of the class variables could also be done, without class instance creation.
Let us suppose that one wishes to make Bicycle objects and then to assign them number starting from 1, for the 1st object. Such Id number would be unique to every object and hence is the instance variable. Similarly, field is needed so that to track the number of Bicycle objects created so to be aware that which ID shall be assigned to next. These fields have no relation with the individual objects however they are associated with class, as a whole. A class variable is needed for this i.e. numberOfBicycles as following:
Java Code:public class Bicycle{ private int cadence; private int gear; private int speed; // add an instance variable for // the object ID private int id; // add a class variable for the // number of Bicycle objects instantiated private static int numberOfBicycles = 0; ... }









Email Blog Entry
License4J 4.0
Yesterday, 12:23 AM in Java Software