【知识点】
(1)声明枚举变量
Java语言的枚举类型隐式地继承了java.lang.Enum类,它本质上是一个类(class),在声明枚举变量时相当于创建Enum类的实例,特殊之处在于枚举类实例并不能任意新建,只能从枚举类的常量列表中选取,所以,枚举列表中常量实例上就是枚举类的实例对象,使用时要为常量指定枚举类名,格式:枚举名.枚举常量名。
【例题】
Given:
01. public class Rainbow {
02. public enum MyColor {
03. RED(0xff0000), GREEN(0x00ff00),BLUE(0x0000ff);
04. private final int rgb;
05. MyColor(int rgb) { this.rgb = rgb; }
06. public int getRGB() { return rgb; }
07. };
08. publicstatic void main(String[] args) {
09. //insert code here
10. }
11. }
Which code fragment, inserted at line 9,allows the Rainbow class to compile?
A. MyColor skyColor = BLUE;
B. MyColor treeColor = MyColor.GREEN;
C. if(RED.getRGB() < BLUE.getRGB()) { }
D. Compilation fails due to other error(s) in the code.
E. MyColor purple = new MyColor(0xff00ff);
F. MyColor purple = MyColor.BLUE +MyColor.RED;
【Answer】 B
【例题辨析】
A. 使用枚举常量名未指定枚举类名,正确格式如下:
MyColor skyColor = MyColor .BLUE;
B. 格式正确;
C. 使用枚举常量名未指定枚举类名,正确格式如下:
if(MyColor.RED.getRGB() < MyColor.BLUE.getRGB()) { }
D. 答非所问;
E. 不能用new 创建新的枚举常量对象;
F. 加法操作符“+”不支持枚举类型,也就是枚举变量不能进行加法操作。