View RSS Feed

Java Object

Class Variables

Rate this Entry
by , 04-26-2012 at 04:44 PM (368 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;
        ...
}

Submit "Class Variables" to Facebook Submit "Class Variables" to Digg Submit "Class Variables" to del.icio.us Submit "Class Variables" to StumbleUpon Submit "Class Variables" to Google

Categories
Tutorial

Comments