next up previous
Next: 1.2.7 Java Programs Up: 1.2 Java Mechanics Previous: 1.2.5 The Structure of

1.2.6 Static Members

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 Java code for a static method cannot refer to any instance members including the (non-static) fields of the class because there is no class instance associated with such a method. Static members are really familiar notions from Scheme and C in disguise; static fields behave exactly like ordinary global variables in Scheme or C and static methods behave like ordinary Scheme or C procedures. Java forces these global variables and procedures to be attached to classes in the guise of static fields and static methods.


Finger Exercise: Load your saved program entry.java into the Definitions window of DrJava. Add the following definition of a static field

static Entry sample = new("Matthias","DH 3102","x 5732");
to the Entry class; its order to relative other members does not matter. Then evaluate the following expressions in the Interactions window:
Entry.sample.getName()
Entry.sample.getAddress()
Entry.sample.getPhone()
Did you get the results that you expected? Note that you did not create an instance of the Entry class in the Interactions window.



next up previous
Next: 1.2.7 Java Programs Up: 1.2 Java Mechanics Previous: 1.2.5 The Structure of
Corky Cartwright
2000-01-07