Java Reference
In-Depth Information
The body of the ETemp enum type declares three constants: C1 , C2 , and C3 . You have added a body to the C1
constant. The compiler will transform the code for ETemp into something like the following code:
public enum ETemp {
public static final ETemp C1 = new ETemp() {
// Body of constant C1
public int getValue() {
return 100;
}
};
public static final ETemp C2 = new ETemp();
public static final ETemp C3 = new ETemp();
// Other code goes here
}
Note that the constant C1 is declared of type ETemp and assigned an object using an anonymous class. The ETemp
enum type has no knowledge of the getValue() method defined in the anonymous class. Therefore, it is useless for all
practical purposes because you cannot call the method as ETemp.C1.getValue() .
To let the client code use the getValue() method, you must declare a getValue() method for the ETemp enum
type. If you want all constants of ETemp to override and provide implementation for this method, you need to declare
it as abstract . If you want it to be overridden by some, but not all constants, you need to declare it non-abstract and
provide a default implementation for it. The following code declares a getValue() method for the ETemp enum type,
which returns 0. The C1 constant has its body, which overrides the getValue() method and returns 100 . Note that the
constants C2 and C3 do not have to have a body; they do not need to override the getValue() method. Now, you can
use the getValue() method on the ETemp enum type.
public enum ETemp {
C1 {
// Body of constant C1
public int getValue() {
return 100;
}
},
C2,
C3;
// Provide the default implementation for the getValue() method
public int getValue() {
return 0;
}
}
The following code rewrites the above version of ETemp and declares the getValue() method abstract . An abstract
method for an enum type forces you to provide a body for all constants and override that method. Now all constants have
a body. The body of each constant overrides and provides implementation for the getValue() method.
 
Search WWH ::




Custom Search