下面是一个来自SCJP 6示例的程序。在这里,我们用不同的咖啡大小创建一个enum
,并声明一个名为ounces
的私有变量来获得枚举的盎司值部分。枚举示例解释
我无法理解被覆盖的getLidCode
方法的用法。如何访问getLidCode
方法?
package com.chapter1.Declaration;
enum CoffeSize {
BIG(8), HUGE(10), OVERWHELMING(20) {
public String getLidCode() {
return "B";
}
};
CoffeSize(int ounce) {
this.ounce = ounce;
}
private int ounce;
public int getOunce() {
return ounce;
}
public void setOunce(int ounce) {
this.ounce = ounce;
}
public String getLidCode() {
return "A";
}
}
public class Prog7 {
CoffeeSize size;
public static void main(String[] args) {
Prog7 p = new Prog7();
p.size = CoffeeSize.OVERWHELMING;
System.out.println(p.size.getOunces());
//p.size.getLidCode(); ? is this correct way
}
}
简而言之,是的,这是正确的做法。 'p.size.getLidCode();'给你'B'。 – pad