Java Reference
In-Depth Information
tions; the
toString()
method is overridden for the “book” value of this enum.
Example 8-4. structure/MediaFancy.java
/** An example of an enum with method overriding */
public
public enum
enum
MediaFancy
{
/** The enum constant for a book, with a method override */
BOOK
{
public
public
String
toString
() {
return
return
"Book"
; }
},
/** The enum constant for a Music CD */
MUSIC_CD
,
/** ... */
MUSIC_VINYL
,
MOVIE_VHS
,
MOVIE_DVD
;
/** It is generally disparaged to have a main() in an enum;
* please forgive this tiny demo class for doing so.
*/
public
public static
void
main
(
String
[]
args
) {
MediaFancy
[]
data
= {
BOOK
,
MOVIE_DVD
,
MUSIC_VINYL
};
for
static
void
for
(
MediaFancy mf
:
data
) {
System
.
out
.
println
(
mf
);
}
}
}
Running the
MediaFancy
program produces this output:
Book
MOVIE_DVD
MUSIC_VINYL
That is, the
Book
values print in a “user-friendly” way compared to the default way the other
values print. In real life you'd want to extend this to all the values in the
enum
.
enum
can take on; simply iterate over the array returned by the enum class's inherited
val-
ues()
method.
Example 8-5. structure/EnumList.java