next up previous
Next: 1.1.4 Capitalization and Commenting Up: 1.1 Introduction Previous: 1.1.2 Classes: Templates for

1.1.3 Defining Constants

In addition to (instance) members (shown in the Entry class above), a Java class can include static members that are attached to the class rather than instances of the class. The static members of a class are not included in the template used to create class instances. There is only one copy of a static field for an entire class--regardless of how many instances of the class are created (possibly none). The most important use of static fields is to hold program constants. We will discuss static methods later in this monograph.

In Java, each program constant is attached to an appropriate class as a static final field of that class. The final attribute indicates that the field is a constant. For example, the built-in Java class Integer includes the constant static final fields int MIN_VALUE and int MAX_VALUE specifying the minimum and maximum values of int type.

The following Java class defines two constants: INCHES_PER_METER and METERS_PER_INCH:

class Conversions {
  static final double INCHES_PER_METER = 39.37;	
  static final double METERS_PER_INCH = .0254;	
}

Outside of the Conversions class, these two contants are denoted

Conversions.INCHES_PER_METER
and
Conversions.METERS_PER_INCH,
respectively. The name of a static field is prefixed by the name of the class in which it is defined, e.g., Conversions.INCHES_PER_METER.


Finger Exercise: In the Definitions pane of DrJava, enter the Conversions class given above. Define a class Person with two fields name and height and three methods getName, getHeightInMeters, and getHeightInInches. Test your Person class by creating several different instances and applying all three methods to them.


next up previous
Next: 1.1.4 Capitalization and Commenting Up: 1.1 Introduction Previous: 1.1.2 Classes: Templates for
Corky Cartwright 2003-07-07