enum的基础代码,就一个地方看不懂,请看注释。
import static net.mindview.util.Print.*;public enum OzWitch {
WEST("Miss Gulch, aka the Wicked Witch of the West"), //从输出结果看出,WEST和“(...)”中的内容是隔开
//的,那么这算什么呢?WEST 是常量、(...)的内容是值?如果要把二者分开来就必须通过将值赋给 String 类型?
NORTH("Glinda, the Good Witch of the North"),
EAST("Wicked Witch of the East, wearer of the Ruby " +
"Slippers, crushed by Dorothy's house"),
SOUTH("Good by inference, but missing");
private String description;
private OzWitch(String description) {
this.description = description;
}
public String getDescription() { return description; }
public static void main(String[] args) {
for(OzWitch witch : OzWitch.values())
print(witch + ": " + witch.getDescription());
}
}
import static net.mindview.util.Print.*;public enum OzWitch {
WEST("Miss Gulch, aka the Wicked Witch of the West"), //从输出结果看出,WEST和“(...)”中的内容是隔开
//的,那么这算什么呢?WEST 是常量、(...)的内容是值?如果要把二者分开来就必须通过将值赋给 String 类型?
NORTH("Glinda, the Good Witch of the North"),
EAST("Wicked Witch of the East, wearer of the Ruby " +
"Slippers, crushed by Dorothy's house"),
SOUTH("Good by inference, but missing");
private String description;
private OzWitch(String description) {
this.description = description;
}
public String getDescription() { return description; }
public static void main(String[] args) {
for(OzWitch witch : OzWitch.values())
print(witch + ": " + witch.getDescription());
}
}
WEST("Miss Gulch, aka the Wicked Witch of the West"), // WEST,NORTH等表示枚举常量,只能取这四个值之一。后面括号里面的是描述(description)
NORTH("Glinda, the Good Witch of the North"),
EAST("Wicked Witch of the East, wearer of the Ruby " +
"Slippers, crushed by Dorothy's house"),
SOUTH("Good by inference, but missing"); private String description;
private OzWitch(String description) {
this.description = description;
}
public String getDescription() { return description; }
public static void main(String[] args) {
/**
* for...each循环,用来对集合进行遍历,得到每一项。是jdk1.5新增加的。
*格式:for(类型 名称:集合名)
* 因为都是OzWitch类型,所以定义为OzWitch witch : OzWitch.values()
*OzWitch.values()----> 返回OzWitch的枚举常量
*/
for(OzWitch witch : OzWitch.values()){
// 得到每一项,调用每一项的getDescription();然后打印出来
System.out.println(witch + ": " + witch.getDescription());
}
private OzWitch(String description) {
this.description = description;
}你定义了一个OzWitch(String description)构造方法
WEST("Miss Gulch, aka the Wicked Witch of the West"),
上面这句就是你调用了这个构造方法,WEST是枚举常量,
("Miss Gulch, aka the Wicked Witch of the West"), 就是你构造方法里面的参数(String description)你在最后又调用了getDescription方法;所以结果就为:
WEST:Miss Gulch, aka the Wicked Witch of the West;
NORTH:Glinda, the Good Witch of the North;
EAST:Wicked Witch of the East, wearer of the Ruby " +
"Slippers, crushed by Dorothy's house; SOUTH:Good by inference, but missing;