Enum class body feature in Java 1.6
What you call a Constant Specific Class Body is what the JLS refers to as an optional class body for an enum constant. It's implemented as an anonymous inner class that extends the outer, enclosing enum. So in your case, the enum constant OVERWHELMING
will be of an anonymous inner type that extends CoffeeSize
, and overrides the method getLidCode()
. In pseudocode, the inner class looks something like this:
class CoffeeSize$1 extends CoffeeSize {
@Override
public String getLidCode() {
return "A";
}
}
Calling getLidCode()
on either the constant BIG
or HUGE
will invoke the base enums implementation, whereas invoking the same method on OVERWHELMING
will invoke the overriden version of the method, since OVERWHELMING
is actually of a different type. To test, simply run code to invoke the getLidCode()
of the different enum constants.
System.out.println(CoffeeSize.BIG.getLidCode());
System.out.println(CoffeeSize.HUGE.getLidCode());
System.out.println(CoffeeSize.OVERWHELMING.getLidCode());
I have executed my answer,as below.Please correct me if im wrong.output is given.
Cheers :-))
public class EnumOverriddenExample {
enum CoffeeSize{
BIG(8),
HUGE(10),
OVERWHELMING(16){
public String getLidCode(){
return "A";
}
};
CoffeeSize(int ounces){
this.ounces = ounces;
}
private int ounces;
public int getOunces(){
return ounces;
}
public void setOunces(int ounces){
this.ounces=ounces;
}
public String getLidCode(){
return "B";
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("CoffeeSize for BIG is "+EnumOverriddenExample.CoffeeSize.BIG.getLidCode());
System.out.println("CoffeeSize for HUGE is "+EnumOverriddenExample.CoffeeSize.HUGE.getLidCode());
System.out.println("CoffeeSize for OVERWHELMING is "+EnumOverriddenExample.CoffeeSize.OVERWHELMING.getLidCode());
System.out.println("CoffeeSize for BIG is "+EnumOverriddenExample.CoffeeSize.BIG.getOunces());
System.out.println("CoffeeSize for HUGE is "+EnumOverriddenExample.CoffeeSize.HUGE.getOunces());
System.out.println("CoffeeSize for OVERWHELMING is "+EnumOverriddenExample.CoffeeSize.OVERWHELMING.getOunces());
}
}
Output is below
-----------------------------------
CoffeeSize for BIG is B --> returns "B"
CoffeeSize for HUGE is B -->returns "B"
CoffeeSize for OVERWHELMING is A--constant specific class body returns "A"
CoffeeSize for BIG is 8
CoffeeSize for HUGE is 10
CoffeeSize for OVERWHELMING is 16
------------------------------------