我仍然不清楚一件事,为什么人们只使用接口来存储常量......当 java 5 提出了它的 Enums 的新功能时......
interface OlympicMedal {
static final String GOLD = "Gold";
static final String SILVER = "Silver";
static final String BRONZE = "Bronze";
}
另一个班级现在正在实施它..
public class OlympicAthlete implements OlympicMedal {
public OlympicAthlete( int aId ){
//..elided
}
//..elided
public void winEvent( ){
//the athlete gets a gold medal
//note the reference is not qualified, as
//in OlympicMedal.GOLD
fMedal = GOLD;
}
// PRIVATE //
private String fMedal; //possibly null
}
如上所示,同样的事情也可以通过枚举轻松建立,如果我可以选择存储上面的常量,我应该选择枚举还是接口..!
枚举就像...
public enum OlympicMedal {
GOLD, SILVER, BRONZ
}
但是请告知该类现在将如何访问此常量..!!