Static, Final, and Enumerated Types in Java
-
What Field Modifier static Means
-
What Field Modifier final Means
-
Why Enumerate a Type?
-
Statements Updated for Enumerations
-
More Complicated Enumerated Types
-
Some Light ReliefThe Haunted Zen Garden of Apple
Enumerated types were brought into Java with the JDK 1.5 release. They are not a new idea in programming, and lots of other languages already have them. The word "enumerate" means "to specify individually". An enumerated type is one where we specify individually (as words) all the legal values for that type. |
For a type that represents t-shirt sizes, the values might be small, medium, large, extraLarge. For a bread flavors type, some values could be wholewheat, ninegrain, rye, french, sourdough. A DaysOfTheWeek enumerated type will have legal values of Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.
The values have to be identifiers. In the USA, ladies' dress sizes are 2, 4, 6, 8, 10, 12, 14, 16. As a Java enumeration, that would have to be represented in words as two, four, or any other characters that form an identifier, such as size2, size4 etc.
When you declare a variable that belongs to an enumerated type, it can only hold one value at a time, and it can't hold values from some other type. A t-shirt size enum variable can't hold "large" and "small" simultaneously, just as an int can't hold two values simultaneously. You can't assign "Monday" to a t-shirt size variable. Though enumerated types aren't essential, they make some kinds of code more readable.
enum is a new keyword
Although JDK 1.5 introduced extensive language changes, "enum" is the only new keyword brought into the language. If any of your existing programs use the word "enum" as an identifier, you will have to change them before you can use JDK.5 features.
The identifier enum might well be in programs that use the older class java.util.Enumeration. That class has nothing to do with the enum type, but is a way of iterating through all the objects in a data structure class. Many people (including me) declared variables such as
java.util.Enumeration enum;
The java.util.Enumeration class has been obsoleted by a class called Iterator, also in the java.util package, so if you're updating some code to change a variable called "enum", you might want to modify it to use an iterator too. We cover iterators in Chapter 16.
Before JDK 1.5, a common way to represent enumerations was with integer constants, like this:
class Bread { static final int wholewheat = 0; static final int ninegrain = 1; static final int rye = 2; static final int french = 3; }
then later
int todaysLoaf = rye;
In the new enum scheme, enumerations are references to one of a fixed set of objects that represent the various possible values. Each object representing one of the choices knows where it fits in the order, its name, and optionally other information as well. Because enum types are implemented as classes, you can add your own methods to them!
The main purpose of this chapter is to describe enumerated types in detail. To do that, we first need to explain what the field modifiers "static" and "final" mean. Here's the story in brief:
-
The keyword final makes the declaration a constant.
-
The keyword static makes the declaration belong to the class as a whole. A static field is shared by all instances of the class, instead of each instance having its own version of the field. A static method does not have a "this" object. A static method can operate on someone else's objects, but not via an implicit or explicit this.
The method where execution starts, main(), is a static method. The purpose of main() is to be an entry point to your code, not to track the state of one individual object. Static "per-class" declarations are different from all the "per-object" data you have seen to date.
The values in enumerated types are always implicitly static and final. The next two sections, What Field Modifier static Means and What Field Modifier final Means, have a longer explanation of the practical effect of these field modifiers. After that, we'll get into enumerated types themselves.
What Field Modifier static Means
We have seen how a class defines the fields and methods that are in an object, and how each object has its own storage for these members. That is usually what you want.
Sometimes, however, there are fields of which you want only one copy, no matter how many instances of the class exist. A good example is a field that represents a total. The objects contain the individual amounts, and you want a single field that represents the total over all the existing objects of that class. There is an obvious place to put this kind of "one-per-class" field tooin a single object that represents the class. Static fields are sometimes called "class variables" because of this.
You could put a total field in every object, but when the total changes you would need to update every object. By making total a static field, any object that wants to reference total knows it isn't instance data. Instead it goes to the class and accesses the single copy there. There aren't multiple copies of a static field, so you can't get multiple inconsistent totals.
Static is a really poor name
Of all the many poorly chosen names in Java, "static" is the worst. The keyword is carried over from the C language, where it was applied to storage which can be allocated statically (at compile time). Whenever you see "static" in Java, think "once-only" or "one-per-class."
What you can make static
You can apply the modifier static to four things in Java:
-
Data. This is a field that belongs to the class, not a field that is stored in each individual object.
-
Methods. These are methods that belong to the class, not individual objects.
-
Blocks. These are blocks within a class that are executed only once, usually for some initialization. They are like instance initializers, but execute once per class, not once per object.
-
Classes. These are classes that are nested in another class. Static classes were introduced with JDK 1.1.
We'll describe static data and static methods in this chapter. Static blocks and static classes are dealt with later on.
Static data
Static data belongs to the class, not an individual object of the class. There is exactly one instance of static data, regardless of how many objects of the class there are. To make a field "per-class," apply the keyword "static," as shown here.
class Employee { int id; // per-object field int salary; // per-object field static int total; // per-class field (one only) ... }
Every Employee object will have the employee_id and salary fields. There will be one field called totalPayroll stored elsewhere in an object representing the Employee class.
Because static data is declared in the class right next to the instance data, it's all too easy to overlook that static data is not kept in each object with its instance data. Make sure you understand this crucial point before reading on. Figure 6-1 represents the previous code in the form of a diagram.
Figure 6-1 There is one copy of a Static field, shared by each object37810 FN Figure 6-1
In methods inside the class, static data is accessed by giving its name just like instance data.
salary = 90000; total = this.total + this.salary;
It's legal but highly misleading to qualify the name of a static field with "this." The "this" variable points to an instance, but static data doesn't live in an instance. The compiler knows where the static data really is, and generates code to access the field in the class object.
Outside the class, static data can be accessed by prefixing it with the name of the class or the name of an object reference. It is considered poor form to use the object reference method. It confuses the reader into mistaking your static member for an instance member.
Employee newhire = new Employee(); // static reference through the class (preferred) Employee.total += 100000;
Static methods
Just as there can be static data that belongs to the class as a whole, there can also be static methods, also called class methods. A class method does some class-wide operations and is not applied to an individual object. Again, these are indicated by using the static modifier before the method name.
The main() method where execution starts is static.
public static void main(String[] args) {
If main weren't static, if it were an instance method, some magic would be needed to create an instance before calling it, as is done for applets and servlets.
Any method that doesn't use instance data is a candidate to be a static method. The conversion routines in the wrappers for the primitive types are static methods. If you look at the source code for java.lang.Integer, you'll see a routine like this
public static int parseInt(String s) throws NumberFormatException { // statements go here. }
The method is a utility that reads the String passed to it as an argument, and tries to turn it into an int return value. It doesn't do anything with data from a specific Integer object (there isn't even an Integer object involved in the call). So parseInt() is properly declared as static. It wouldn't be actively harmful to make it an instance method, but you would then need to whisk up an otherwise unnecessary Integer object on which to invoke it. Here's an example of calling the static method parseInt:
int i = Integer.parseInt("-2048");
The Java Language Specification says "A class method is always invoked without reference to a particular object" (section 8.4.3.2). So some compilers generate an error if you invoke a static method through an instance variable. Other compilers take the view "it's OK to reach static data through an instance reference (and the JLS has an example of this), so it should be OK for static methods too". Stick to invoking static methods using the class name, to avoid compiler problems and to show other programmers that this a class method.
A common pitfall with static methods
A common pitfall is to reference per-object members from a static method. This "does not compute". A static method isn't invoked on an object and doesn't have the implicit "this" pointer to individual object data, so the compiler won't know which object you want. You'll get an error message saying "Can't make static reference to non-static variable."
Java novices often make this mistake when they write their first class with several methods. They know the main() method has to be static, but they try to invoke the instance methods from inside main. The simplest workaround is to declare an instance of the class in question inside main(), and invoke the methods on that.
class Timestamp { void someMethod() { // ... public static void main(String[] args) { someMethod(); // NO! does not work Timestamp ts = new Timestamp(); ts.someMethod(); // Yes! does work
Another workaround is to add the static modifier to everything you reference. Only use this kludge for small test programs.