Java Reference
In-Depth Information
The other kind of class variable is associated with the class, and is shared by all objects of the class.
There is only one copy of each of these kinds of variables no matter how many class objects are created,
and they exist even if no objects of the class have been created. This kind of variable is referred to as a
class variable because the variable belongs to the class, not to any particular object, although as we have
said, all objects of the class will share it. These variables are also referred to as static fields because, as
we will see, you use the keyword static when you declare them.
Because this is extremely important to understand, let's summarize the two kinds of variables that you
can include in your classes:
Instance variables
Each object of the class will have its own copy of each of the instance variables that appear in
the class definition. Each object will have its own values for each instance variable. The name
'instance variable' originates from the fact that an object is an 'instance' or an occurrence of a
class and the values stored in the instance variables for the object differentiate the object from
others of the same class type. An instance variable is declared within the class definition in the
usual way, with a type name and a variable name, and can have an initial value specified.
Class variables
A given class will only have one copy of each of its class variables, and these will be shared
between all the objects of the class. The class variables exist even if no objects of the class
have been created. They belong to the class, and they can be referenced by any object or
class, not just instances of that class. If the value of a class variable is changed, the new value
is available in all the objects of the class. This is quite different from instance variables where
changing a value for one object does not affect the values in other objects. A class variable
must be declared using the keyword static preceding the type name.
Look at the following diagram, which illustrates the difference between the two:
Class
Sphere
Definition
Shared between all objects
Sphere.PI
3.14
globe
xCenter
yCenter
zCenter
radius
public class Sphere {
// class variable
static double PI=3.14;
// instance variables
double xCenter;
double yCenter;
double zCenter;
double radius;
Each object gets
its own copy
Sphere Objects
}
ball
xCenter
yCenter
zCenter
radius
This shows a schematic of a class Sphere with one class variable PI , and four instance variables,
radius , xCenter , yCenter , and zCenter . Each of the objects, globe and ball , will have their
own variables, radius , xCenter , yCenter , and zCenter , but both will share a single copy of the
class variable PI .
Search WWH ::




Custom Search