Java Reference
In-Depth Information
contents of the array of
Jacket
objects. This also involves an implicit call to the
toString()
method for
each
Jacket
object.
Because you have defined the
JacketSize
and
JacketColor
enumerations in separate classes, they are
accessible from any source file in the same directory. To make them even more widely available, you
could put them in a package.
The
Jacket
class uses the enumeration types to define private fields recording the size and color of a
jacket. Note how the
toString()
method in the
Jacket
class is able to use the size and color members
as though they were strings. The compiler inserts a call to the
toString()
method for the enumeration
type that applies. You can override the
toString()
method for an enumeration type. For example, you
might decide you prefer to define the
toString()
method in the
JacketSize
enumeration like this:
@Override
public String toString() {
switch(this) {
case small:
return "S";
case medium:
return "M";
case large:
return "L";
case extra_large:
return "XL";
default:
return "XXL";
}
}
Note how you can use
this
as the control expression for the
switch
statement. This is because
this
references the current instance, which is an enumeration constant. Because the expression is an enumera-
tion constant, the case labels are the constant names. They do not need to be qualified by the name of the
enumeration. With this implementation of
toString()
in the
JacketSize
enumeration, the output is:
Jackets colors available are:
red orange yellow blue green
Jackets sizes available are:
S M L XL XXL
Jackets in stock are:
Jacket M in red
Jacket XL in yellow
Jacket S in green
Jacket XXL in blue
Thus, you can see from this example that you can treat an enumeration type just like any other class type.