Deepak Deepak - 9 months ago 25
Java Question

Enum class body feature in Java 1.6

enum CoffeeSize{
BIG(8),
HUGE(10),
OVERWHELMING(16) {

public String getLidCode(){
return "A";
}
};

private int ounces;

public int getOunces(){
return ounces;
}

CoffeeSize(int ounces){
this.ounces = ounces;
}

public String getLidCode(){
return "B";
}
}


This is a SCJP 1.6 question from K&B 6 book.
This is an example of Constant Specific Class Body as a feature of SCJP 6. How do I execute this and see the resultant output?

I have 2 questions:


  1. What does my Java main method look like ?Please help me to execute this partial code. I'm unable to understand how the output behaves.

  2. How does the
    getLidCode()
    method work in this class body in Java 1.6 ?


Answer Source

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(). The inner class looks, in pseudocode, 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());