enum
base
- 常見(jiàn)的枚舉使用場(chǎng)景十分簡(jiǎn)單突硝。舉個(gè)例子再悼,寫(xiě)個(gè)枚舉類(lèi)標(biāo)記不同的水果陶衅。
public enum Fruit {
APPLE,
ORANGE,
BANANA;
}
Advanced 1
- 進(jìn)階為水果加上中文名稱(chēng)??
public enum Fruit {
APPLE("蘋(píng)果"),
ORANGE("橘子"),
BANANA("香蕉");
public final String cnName;
Fruit(String cnName) {
this.cnName = cnName;
}
}
- eg. 獲取中文名稱(chēng)
System.out.ptintln(Frut.APPLE.cnName);
System.out.ptintln(Frut.ORANGE.cnName);
System.out.ptintln(Frut.BANANA.cnName);
Advance 2
- 不同的水果有不同的處理方式诵竭,比如香蕉需要包皮了才能夠吃脯宿,那么為不同的水果加上不同的預(yù)處理方式.
public enum Fruit {
APPLE("蘋(píng)果"){
@Override
public void preHandle() {
super.preHandle();
System.out.println("啊啊啊囱桨,我被削皮了");
}
},
ORANGE("橘子"){
@Override
public void preHandle() {
super.preHandle();
System.out.println("啊啊啊,我被剝皮了");
}
},
BANANA("香蕉"){
@Override
public void preHandle() {
super.preHandle();
System.out.println("啊啊啊嗅绰,我被剝皮了");
}
};
public final String cnName;
Fruit(String cnName) {
this.cnName = cnName;
}
public void preHandle() {
System.out.println(this.name() + ":開(kāi)始被預(yù)處理了");
}
public static void main(String[] args) {
Fruit.APPLE.preHandle();
}
}
- eg 運(yùn)行程序中的main方法舍肠。可以得到如下輸出
Connected to the target VM, address: '127.0.0.1:62224', transport: 'socket'
APPLE:開(kāi)始被預(yù)處理了
啊啊啊窘面,我被削皮了
Disconnected from the target VM, address: '127.0.0.1:62224', transport: 'socket'
??♂?是不是很神奇翠语,有沒(méi)有些頓悟啦,是不是很多操作都可以用這種方法標(biāo)記呢财边?