Java Reference
In-Depth Information
Behind the scenes, the compiler converts enum Coin { PENNY, ICKEL,
DIME, QUARTER } into a class declaration that is similar to Listing 3-66 .
Thefollowingrulesshowyouhowtointerpret Enum<E extends Enum<E>> in
the context of Coin extends Enum<Coin> :
• Anysubclass of Enum mustsupplyanactual typeargumentto Enum .Forex-
ample, Coin 's header specifies Enum<Coin> .
• Theactualtypeargumentmustbeasubclassof Enum .Forexample, Coin isa
subclass of Enum .
• A subclass of Enum (such as Coin ) must follow the idiom that it supplies its
own name ( Coin ) as an actual type argument.
Thethirdruleallows Enum todeclaremethods— compareTo() , getDeclarin-
gClass() , and valueOf() —whose parameter and/or return types are specified in
termsofthesubclass( Coin ),andnotintermsof Enum .Therationalefordoingthisis
to avoid having to specify casts. For example, you do not need to cast valueOf() 's
return value to Coin in Coin penny = Enum.valueOf(Coin.class,
"PENNY"); .
Note You cannot compile Listing 3-66 because the compiler will not compile any
class that extends Enum . It will also complain about super(name, ordinal); .
EXERCISES
The following exercises are designed to test your understanding of nested types,
packages, static imports, exceptions, assertions, annotations, generics, and enums:
1. A 2D graphics package supports two-dimensional drawing and transform-
ations (rotation, scaling, translation, and so on). These transformations re-
quire a 3-by-3 matrix (a table). Declare a G2D class that encloses a
private Matrix nonstaticmemberclass.Inadditiontodeclaringa Mat-
rix(int rows, int cols) constructor, Matrix declares a void
dump() methodthatoutputsthematrixvaluestostandardoutputinatab-
ularformat.Instantiate Matrix within G2D 'snoargumentconstructor,and
initialize the Matrix instance to the identity matrix (a matrix where all
entriesare0exceptforthoseontheupper-lefttolower-rightdiagonal,which
are1.Theninvokethisinstance's dump() methodfromtheconstructor.In-
clude a main() method to test G2D .
Search WWH ::




Custom Search