WebReference.com - Part 1 of chapter 5 from Beginning Java 2 SDK 1.4 Edition, Wrox Press Ltd (2/8) | WebReference

WebReference.com - Part 1 of chapter 5 from Beginning Java 2 SDK 1.4 Edition, Wrox Press Ltd (2/8)

To page 1current pageTo page 3To page 4To page 5To page 6To page 7To page 8
[previous] [next]

Beginning Java 2 SDK 1.4 Edition

Because this is extremely important to understand, let's summarize the two kinds of variables that you can include in your classes:

Look at the following diagram, which illustrates the difference between the two:

schematic of the class Sphere

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.

Why would you need two kinds of variables in a class definition? The instance variables are clearly necessary since they are the parameters that distinguish a particular object. 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 a sphere--to calculate the volume for example--it would be wasteful to store a value for PI in every object, since it is always the same. Incidentally, 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 Pi that are common to all objects of the class.

Another use for class variables is to track data values that are common to all objects of a class, and that need to be available even when no objects have been defined. For example, if you wanted to keep a count of how many objects of a class have been created in your program, you would define the variable storing the count as a class variable. It would be essential to use a class variable, because you would still want to be able to use your count variable even when no objects have been declared.


To page 1current pageTo page 3To page 4To page 5To page 6To page 7To page 8
[previous] [next]

Created: June 24, 2002
Revised: June 24, 2002


URL: https://webreference.com/programming/java/beginning/chap5/1/2.html