next up previous
Next: 1.5.2 Local variables Up: 1.5 Loose Ends Previous: 1.5 Loose Ends

1.5.1 Static members

Classes in Java play two complementary roles; they serve:

Not all phases of a computation have a natural object-oriented formulation. Java provides static methods and fields to deal with these situations.

A static field s in a class C is simply a global variable named C.s. Similarly, a static method m in class C is simply a procedure named C.m. Static members are associated with classes rather than objects. Hence, static members exist and can be accessed even when the corresponding class is never instantiated or extended.

One important use of static fields is storing the canonical instance of a class that only needs a single instance. For example, the Empty subclass of DeptDirectory only needs one instance because the class has no (dynamic) fields.

class Empty extends DeptDirectory{
  ...

  static Empty soleInstance = new Empty();
}

Instead of allocating new instances of Empty, code can simply refer to the canonical instance Empty.soleInstance.

Static fields are also used to hold program constants. For example, the library class Integer includes the following static fields among others:

public static final int MAX_VALUE;
public static final int MIN_VALUE;
The final attribute indicates that the values of the fields cannot be modified.

Conventional procedures are necessary in Java for a variety or reasons including:

For example, the built-in Integer includes a static method

public String toString(int value);
that converts a primitive int value to its printable String form. Since int values are not objects, this operation cannot be formulated in object-oriented style.

Similarly, an operation

public String squeezeWhiteSpace(String s);
that returns a String identical to s with all spaces and tabs removed must be expressed as a static method because the library String class cannot be modified or extended.

Finally, all operations on arrays must be expressed in static (procedural) form because array types do not have conventional class definitions; they are built-in to the Java virtual machine.


next up previous
Next: 1.5.2 Local variables Up: 1.5 Loose Ends Previous: 1.5 Loose Ends
Robert Cartwright, Spring 1999