Java Reference
In-Depth Information
introduce. Let's take an example. Suppose you want to define an enumeration for clothing sizes — jackets,
say. Your initial definition might be like this:
public enum JacketSize { small, medium, large, extra_large, extra_extra_large }
You then realize that you would really like to record the average chest size applicable to each jacket size.
You could amend the definition of the enumeration like this:
public enum JacketSize {
small(36), medium(40), large(42), extra_large(46), extra_extra_large(48);
// Constructor
JacketSize(int chestSize) {
this.chestSize = chestSize;
}
// Method to return the chest size for the current jacket size
public int chestSize() {
return chestSize;
}
private int chestSize;
// Field to record chest size
}
Directory "TryJackets"
Note how the list of enumeration constants now ends with a semicolon. Each constant in the list has the
corresponding chest size between parentheses, and this value is passed to the constructor that you have ad-
ded to the class. In the previous definition of JacketSize , the appearance of each enumeration constant res-
ults in a call to the default constructor for the class. In fact, you could put an empty pair of parentheses after
the name of each constant, and it would still compile. However, this would not improve the clarity of the
code. Because you have defined a constructor, no default constructor is defined for the enumeration class,
so you cannot write enumeration constants just as names. You must put the parentheses enclosing a value
for the chest size following each enumeration constant. Of course, if you want to have the option of omitting
the chest size for some of the constants in the enumeration, you can define your own default constructor and
assign a default value for the chestSize field.
Even though you have added your own constructor, the fields inherited from the base class, Enum , that
store the name of the constant and its ordinal value are still set appropriately. The ordering of the constants
that compareTo() implements are still determined by the sequence in which the constants appear in the
definition. Note that you must not declare a constructor in an enumeration class as public . If you do, the
enum class definition does not compile. The only modifier that you are allowed to apply to a constructor in
a class defining an enumeration is private , which results in the constructor being callable only from inside
the class.
The chest size is recorded in a private data member so there is also a chestSize() method to allow the
value of chestSize to be retrieved.
Let's see it working.
Search WWH ::




Custom Search