这是取自 SCJP 6 示例的程序。在这里,我们创建一个具有不同咖啡尺寸的enum
,并声明一个名为ounces
的私有(private)变量来获取枚举的盎司值部分。
我无法理解被重写的 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
}
}
最佳答案
如果你把它间隔得更大一点,那就更有意义了:
enum CoffeSize {
BIG(8),
HUGE(10),
OVERWHELMING(20) {
public String getLidCode() {
return "B";
}
};
// rest of enum code here
}
只有OVERWHELMING
会覆盖getLidCode()
。
您可以通过此方法访问它(使用您的代码):
System.out.println(p.size.getLidCode());
原因是:p.size
是 CoffeSize
类型,它具有方法 getLidCode()
。它将按预期打印重写方法的值。
关于java - 枚举示例说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18095014/