Java Reference
In-Depth Information
Because this is extremely important to understand, let's summarize the two kinds of fields that you can
include in your classes:
Non-static fields, also called instance variables: Each object of the class has its own copy of
each of the non-static fields or instance variables that appear in the class definition. Each object
has 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 vari-
ables for the object differentiate the object from others of the same class type. You declare an in-
stance variable within the class definition in the usual way, with a type name and a variable name,
and it can have an initial value specified.
Static fields, also called class variables: A given class has only one copy of each of its static
fields or class variables, and these are shared between and among all the objects of the class. Each
class variable exists even if no objects of the class have been created. Class variables belong to
the class, and they can be referenced by any object or class method, not just methods belonging to
instances of that class. If the value of a static field is changed, the new value is available equally
in all the objects of the class. This is quite different from non-static fields, where changing a value
for one object does not affect the values in other objects. A static field must be declared using the
keyword static preceding the type name.
Look at Figure 5-1 , which illustrates the difference between class variables and instance variables.
FIGURE 5-1
Figure 5-1 shows a schematic of a class, Sphere , that has one class variable, PI , and four instance vari-
ables, radius , xCenter , yCenter , and zCenter . Each of the objects, globe and ball , has its own set of
variables with the names radius , xCenter , yCenter , and zCenter , but both share a single copy of the class
variable PI .
Why would you need two kinds of variables in a class definition? The instance variables are clearly ne-
cessary because they store the values that distinguish one particular object from another. The radius and the
coordinates of the center of the sphere are fundamental to determining how big a particular Sphere object
is, and where it is in space. However, although the variable PI is a fundamental parameter for every sphere
— to calculate the volume, for example — it would be wasteful to store a value for PI in every Sphere
object because it is always the same. As you know, it is also available from the standard class Math so it is
somewhat superfluous in this case, but you get the general idea. So, one use for class variables is to hold
constant values such as π that are common to all objects of the class.
 
 
Search WWH ::




Custom Search