以程序穿插知识的方式是我觉得好的方式!
package supplement;
import supplement.FreshJuice.FreshJuiceSize;
/**
* Title:FreshJuiceTest类
* @author fsp
* @version 1.0
*/
class FreshJuice{
/*
* 枚举是一个被命名的整型常数的集合,用于声明一组带标识符的常数。
* 例如,我们为果汁店设计一个程序,它将限制果汁为小杯、中杯、大杯。这就意味着它不允许顾客点除了这三种尺寸外的果汁。
* 类似这种当一个变量有几种固定可能的取值时,就可以将它定义为枚举类型。
* */
enum FreshJuiceSize{
SMALL {
@Override
public void call() {
// TODO Auto-generated method stub
}
},
MEDIUM {
@Override
public void call() {
// TODO Auto-generated method stub
}
},
LARGE {
@Override
public void call() {
// TODO Auto-generated method stub
}
};
private FreshJuiceSize()
{
System.out.println("Constructor called for : " + this.toString());
}
//枚举类的抽象方法实现,需要枚举类中的每个对象都进行实现
public abstract void call();
}
/*
* 每个枚举都是通过 FreshJuiceSize 在内部实现的,且所有的枚举值都是 public static final 的。
* 以上的枚举类 FreshJuiceSize 转化在内部类实现:
*
* */
/*
class FreshJuiceSize{
public static final FreshJuiceSize SMALL = new FreshJuiceSize();
public static final FreshJuiceSize MEDIUM = new FreshJuiceSize();
public static final FreshJuiceSize LARGE = new FreshJuiceSize();
private FreshJuiceSize()
{
System.out.println("Constructor called for : " + this.toString());
}
}
*/
FreshJuiceSize size;
}
public class FreshJuiceTest {
public static void main(String[] args) {
FreshJuice juice = new FreshJuice();
juice.size = FreshJuiceSize.MEDIUM;
switch (juice.size) {
case SMALL:
System.out.println("小");
break;
case MEDIUM:
System.out.println("中");
break;
case LARGE:
System.out.println("大");
break;
default:
break;
}
//可以使用 for 语句来迭代枚举元素:
for(FreshJuiceSize x:FreshJuiceSize.values()) {
System.out.println(x);
}
//使用 valueOf() 返回枚举常量,不存在的会报错 IllegalArgumentException
System.out.println(FreshJuiceSize.valueOf("LARGE"));
}
}