Java Reference
In-Depth Information
name=LOW, ordinal=0, days=30
name=MEDIUM, ordinal=1, days=15
name=HIGH, ordinal=2, days=7
name=URGENT, ordinal=3, days=1
Associating a Body to an Enum Constant
SmartSeverity is an example of adding data and methods to an enum type. The code in the
getProjectedTurnaroundDays() method is the same for all enum constants. You can also associate a different body
to each enum constant. The body can have fields and methods. The body for an enum constant is placed inside
braces following its name. If the enum constant accepts arguments, its body follows its argument list. The syntax for
associating a body to an enum constant is as follows:
<access-modifier> enum <enum-type-name> {
CONST1 {
// Body for CONST1 goes here
},
CONST2 {
// Body for CONST2 goes here
},
CONST3(arguments-list) {
// Body of CONST3 goes here
};
// Other code goes here
}
It is a little different game when you add a body to an enum constant. The compiler creates an anonymous
class, which inherits from the enum type. It moves the body of the enum constant to the body of that anonymous
class. Anonymous classes are covered in Chapter 2 of the topic Beginning Java Language Features
(ISBN:978-1-4302-6658-7). I will use it briefly to complete the discussion of the enum type. For now, you can think of it
just as a different way of declaring and creating a new class at the same time.
Consider an ETemp enum type, as shown:
public enum ETemp {
C1 {
// Body of constant C1
public int getValue() {
return 100;
}
},
C2,
C3;
}
 
Search WWH ::




Custom Search