Java Reference
In-Depth Information
For example, to create an enumerated type for card suits, you could write the fol-
lowing code in a file named Suit.java :
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
}
The following client code uses the enumerated type:
// 9 of Diamonds
int myCardRank = 9;
Suit myCardSuit = Suit.DIAMONDS;
It would also be possible to create a Card class that has a field for the card's rank
and a field of type Suit for the card's suit. This way an invalid suit can never be
passed; it must be one of the four constants declared. You can test whether a variable
of an enumerated type stores a particular value with the == and != operators:
if (myCardSuit == Suit.CLUBS) {
// then this card is a Club
...
}
The enum concept is borrowed from past programming languages such as C, in
which enumerated constants were actually represented as 0-based integers on the
basis of the order in which they were declared. If you want to get an integer equiva-
lent value for a Java enum value, call its ordinal method. For example, the call of
myCardSuit.ordinal() returns 1 because DIAMONDS is the second constant declared.
Every enum type also has a values method that returns all possible values in the enumer-
ation as an array. For example, the call of Suit.values() returns the following array:
{Suit.CLUBS, Suit.DIAMONDS, Suit.HEARTS, Suit.SPADES}
Packages
Since Chapter 3 we have used the import statement to make use of classes from the
Java class libraries. The classes in the libraries are organized into groups called pack-
ages . Packages are valuable when you are working with large numbers of classes.
They give Java multiple namespaces , meaning that there may be two classes with the
same name so long as they are in different packages. Packages also help physically
separate your code files into different directories, which makes it easier to organize a
large Java project.
Every Java class is part of a package. If the class does not specify which package
it belongs to, it is part of a nameless default package. To specify that the class
belongs to some other package, place a package declaration statement as the first
 
Search WWH ::




Custom Search