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:
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.
How does the getLidCode()
method work in this class body in Java 1.6 ?
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With