next up previous
Next: Capitalization and Commenting Conventions Up: Java Mechanics Previous: Printing Object Values

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. Inside the Conversions class, the Conversions. prefix is unnecessary.


Finger Exercise 1.3.7.1: 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. Write a TestPerson class corresponding to Person that creates several different instances of Person and applies all three methods to them. Save your program in a file called Person.java.


next up previous
Next: Capitalization and Commenting Conventions Up: Java Mechanics Previous: Printing Object Values
Corky Cartwright 2004-02-05