Java认证考试实例疑难辨析(11)

【知识点】

(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. 加法操作符“+”不支持枚举类型,也就是枚举变量不能进行加法操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值