这是一个取自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
}
}
Run Code Online (Sandbox Code Playgroud)
如果你把它分开一点,那就更有意义了:
enum CoffeSize {
BIG(8),
HUGE(10),
OVERWHELMING(20) {
public String getLidCode() {
return "B";
}
};
// rest of enum code here
}
Run Code Online (Sandbox Code Playgroud)
只有OVERWHELMING压倒一切getLidCode().
您可以通过这种方法访问它(使用您的代码):
System.out.println(p.size.getLidCode());
Run Code Online (Sandbox Code Playgroud)
原因是: p.size类型CoffeSize,它有方法getLidCode().它将按预期打印重写方法的值.
| 归档时间: |
|
| 查看次数: |
1925 次 |
| 最近记录: |