Java Reference
In-Depth Information
The runtime type is less specific than the compile-time type, because the type infor‐
mation about the payload type is gone—it has been erased, and the resulting run‐
time type is just a raw type.
The compile-time type is less specific than the runtime type, because we don't know
exactly what concrete type l will be—all we know is that it will be of a type compati‐
ble with List .
Enums and Annotations
Java has specialized forms of classes and interfaces that are used to fulfill specific
roles in the type system. They are known as enumerated types and annotation types,
normally just called enums and annotations .
Enums
Enums are a variation of classes that have limited functionality and that have only a
small number of possible values that the type permits.
For example, suppose we want to define a type to represent the primary colors of
red, green, and blue, and we want these to be the only possible values of the type.
We can do this by making use of the enum keyword:
m
e
public enum PrimaryColor {
// The ; is not required at the end of the list of instances
RED , GREEN , BLUE
}
Instances of the type PrimaryColor can then be referenced as though they were
static fields: PrimaryColor.RED , PrimaryColor.GREEN , and PrimaryColor.BLUE .
In other languages, such as C++, this role is usually fulfilled by
using constant integers, but Java's approach provides better
type safety, and more flexiblity. For example, as enums are
specialized classes, enums can have member fields and meth‐
ods. If they do have a body (consisting of fields or methods)
then the semicolon at the end of the list of instances is
required.
For example, suppose that we want to have an enum that encompasses the first few
regular polygons (shapes with all sides and all angles equal), and we want them to
have some behavior (in the form of methods). We could achieve this by using an
enum that takes a value as a parameter, like this:
public enum RegularPolygon {
// The ; is mandatory for enums that have parameters
TRIANGLE ( 3 ), SQUARE ( 4 ), PENTAGON ( 5 ), HEXAGON ( 6 );
private Shape shape ;
Search WWH ::




Custom Search