Method getLidCode
normally returns constant "A". For CoffeSize.BIG
and CoffeSize.HUGE
, it is not overriden, so this is the value they will return. However, for CoffeSize.OVERWHELMING
it's overriden and it will return "B".
If you think of enums as classes and their enum values as instances of that class, enums allows method overriding on a per-object basis. This is not possible with regular classes/objects.
This could also have been implemented as:
enum CoffeSize {
BIG(8,"A"), HUGE(10,"A"), OVERWHELMING(20,"B");
CoffeSize(int ounce,String lidCode) {
this.ounce= ounce ;
this.lidCode= lidCode ;
}
private int ounce;
private String lidCode;
public int getOunce() {
return this.ounce ;
}
public void setOunce(int ounce) {
this.ounce= ounce ;
}
public String getLidCode() {
return this.lidCode ;
}
}
Note that to make this alternate implementation more equivalent to the original one, no setLidCode
method was defined.
The true power of this mechanism can be appreciated more easily in the following example, though:
enum BinaryOperation {
ADDITION("+",1) {
public double operate(double a,double b) {
return a + b ;
}
},
SUBTRACTION("-",1),
MULTIPLICATION("*",2) {
public double operate(double a,double b) {
return a * b ;
}
},
DIVISION("/",2),
POWER("**",3);
BinaryOperation(String repr,int priority) {
this.repr= repr ;
this.priority= priority ;
}
private String repr;
private int priority;
public String toString() {
return this.repr ;
}
public int getPriority() {
return this.priority ;
}
public double operate(double a,double b) {
throw new UnsupportedOperationException() ;
}
}
SUBTRACTION
, DIVISION
, and POWER
will throw an exception when their operate
method is invoked (for some reason, only commutative operations have been implemented at this point). However, BinaryOperation.ADDITION.operate(3.5,2.1)
and BinaryOperation.MULTIPLICATION.operate(4.5,2.0)
will return the expected values (5.6 and 9.0 respectively). This also answers your question about usage. Yes, your tentative example is correct.
There is no simple OO way of implementing this using fields or other mechanisms.