示例1:创建枚举类的Java程序
enum Size{
// enum constants
SMALL, MEDIUM, LARGE, EXTRALARGE;
public String getSize() {
// this will refer to the object SMALL
switch(this) {
case SMALL:
return "small";
case MEDIUM:
return "medium";
case LARGE:
return "large";
case EXTRALARGE:
return "extra large";
default:
return null;
}
}
public static void main(String[] args) {
// call the method getSize()
// using the object SMALL
System.out.println("The size of Pizza I get is " + Size.SMALL.getSize());
// call the method getSize()
// using the object LARGE
System.out.println("The size of Pizza I want is " + Size.LARGE.getSize());
}
}
输出
The size of Pizza I get is small
The size of Pizza I want is large
在上面的示例中,我们创建了一个名为Size的枚举类。该类包含四个常量SMALL , MEDIUM , LARGE和EXTRALARGE 。
在这里,编译器自动将枚举的所有常量转换为它的实例。因此,我们可以使用常量作为对象来调用该方法。
Size.SMALL.getSize()
在此调用中, this
关键字现在与SMALL对象关联。因此,返回小值。