Java Reference
In-Depth Information
The following output is produced. As you can see, the traffic light cycles through the
colors in order of green, yellow, and red:
In the program, notice how the use of the enumeration simplifies and adds structure
to the code that needs to know the state of the traffic light. Because the light can have
only three states (red, green, or yellow), the use of an enumeration ensures that only
these values are valid, thus preventing accidental misuse.
9 . It is possible to improve the preceding program by taking advantage of the class cap-
abilities of an enumeration. For example, by adding a constructor, instance variable,
and method to TrafficLightColor , you can substantially improve the preceding pro-
gramming. This improvement is left as an exercise. See Self Test, question 4.
Autoboxing
Beginning with JDK 5, Java has included two very helpful features: autoboxing and auto-
unboxing . Autoboxing/unboxing greatly simplifies and streamlines code that must convert
primitive types into objects, and vice versa. Because such situations are found frequently
in Java code, the benefits of autoboxing/unboxing affect nearly all Java programmers. As
you will see in Chapter 13 , autoboxing/unboxing also contributes greatly to the usability of
generics.
Autoboxing/unboxing is directly related to Java's type wrappers, and to the way that val-
ues are moved into and out of an instance of a wrapper. For this reason, we will begin with
an overview of the type wrappers and the process of manually boxing and unboxing values.
Search WWH ::




Custom Search