CHAPTER 2 ■ JAVA SYNTAX
On a field, the static keyword has a similar effect as it does on a method: A static field has one
instance that's used by all the objects defined by that class. Consequently, a static field is also known as a
class field (because it applies only to the class, not to the objects created from the class). Static fields are
mostly used to define constants (values that never change). We get to constants later in this chapter.
■ Warning Static fields can cause problems. Suppose you have two parts of a program running at once, each of
which is working with an object whose class definition has a static field. If both classes try to modify the field at
the same time, bad things (including both race conditions—parts of the program waiting for one another—and the
field's value not being correct) can happen. For this reason, all static fields other than constants (which are both
static and final) should usually be private.
Constants
Many programming languages support the concept of a constant. A constant is a value that never
changes. For example, Java includes a class called Math, and the Math class includes a constant called PI,
which holds the value of Pi to a high level of precision.
In Java, a constant is a field with a particular set of modifiers: static and final. Most are also public,
though it is possible (and sometimes useful) to have private, package, and protected constants. We use a
private constant in the AverageImpl class to avoid typing the same string twice. By convention, the
names of constants are all uppercase and have underscores between the units that are logically words as
in Listing 2-9.
Listing 2-9. A constant
private static final String EXCEPTION_MESSAGE =
"ints must contain at least one int";
Methods
A method is basically something that a class can do. One common metaphor for classes and objects is
that classes are nouns and methods are verbs. As with all metaphors, it's sometimes true and sometimes
false, but it's often a handy way to check whether your design makes sense. Methods often do something
with the other members (fields and methods) of the class. However, some methods (usually static
methods) do nothing with the other members of the class, effectively operating on their own.
Thanks to the capability of methods to do lots of different things, it's hard to make a meaningful
generalization about methods beyond just saying, “Methods do things.” Perhaps some examples will
help (see Listing 2-10).