您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)

 
 
Content Index
Content Page # 27

Examples of class variables (and constants)

Classes with class constants provide constant (final) variables for reference. A good example is the PI class constant of the Math class:
 

Math.PI;
g.drawString ("Math.PI =: " + Math.PI, 20, 20);


There is no need for any instance of the class to be created for some other other object to be able to refer to this value. Notice that the dot notation is used for class variables and constants, but with the class identifier rather than an object variable first. The general form for referring to class constants and variables is as follows:

<classIdentifier>.<variable>
or if the class is within a package:
<package>.<classIdentifier>.<variable>
A class constant or variable is declared in the same way as an instance constant or variable, except that the static keyword is included. So for example, a Client class might declare a class variable to count the number of Client objects that have been created. Such a variable would be declared as follows:
private static int numClients = 0;
Regardless of how many objects of the class existing, since this is a static variable, this will be the only occurance of the variable numClients. Objects of the Client class can update or read the variable, but since the variable is private, objects of other classes will not be able to read or update this variable.

There are a number of situations where it is useful to have class variables, although they are not that relevant to the programs you will be developing for this module. It is are recommended you carefully study Deitel & Deitel to learn more about the use of the static keyword to define class variables and constants.

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg