使用枚举类型设置常量

  通常在接口中设置常量,并且该常量不能被修改。因为在接口中定义常量时,该常量被修饰为static和final类型。在调用时不能检测参数的类型,而枚举类型定义的常量参数在调用时可以检测参数的类型。

以下面例子说用枚举类型与与接口定义常量的区别

例:

 1 interface Constants { // 将常量放置在接口中
 2     public static final int Constants_A = 1;
 3     public static final int Constants_B = 12;
 4 }
 5 
 6 public class ConstantsTest {
 7     enum Constants2 { // 将常量放置在枚举类型中
 8         Constants_A, Constants_B
 9     }
10 
11     // 使用接口定义常量
12     public static void doit(int c) { // 定义一个方法,这里的参数为int型
13         switch (c) { // 根据常量的值做不同操作
14         case Constants.Constants_A:
15             System.out.println("doit() Constants_A");
16             break;
17         case Constants.Constants_B:
18             System.out.println("doit() Constants_B");
19             break;
20         }
21     }
22 
23     /** 定义一个方法,这里的参数为枚举类型对象 */
24     public static void doit2(Constants2 c) {
25         switch (c) { // 根据枚举类型对象做不同操作
26         case Constants_A:
27             System.out.println("doit2() Constants_A");
28             break;
29         case Constants_B:
30             System.out.println("doit2() Constants_B");
31             break;
32         }
33     }
34 
35     public static void main(String[] args) {
36         ConstantsTest.doit(Constants.Constants_A); // 使用接口中定义的常量
37         ConstantsTest.doit(12);
38         ConstantsTest.doit(Constants.Constants_B);
39         ConstantsTest.doit2(Constants2.Constants_A); // 使用枚举类型中的常量
40         ConstantsTest.doit2(Constants2.Constants_B); // 使用枚举类型中的常量
41         ConstantsTest.doit(2);
42         //ConstantsTest.doit2(2);             //  报错
43     }
44 }

运行结果:

doit() Constants_A
doit() Constants_B
doit() Constants_B
doit2() Constants_A
doit2() Constants_B

分析:在上述代码中,当用户调用doit()方法时,编译器不接受在接口中定义的常量参数,也不会报错,但调用doit2()方法时,任意传递的参数,编译器就会报错,因为这个方法只接受枚举类型的常量作为其参数。

 

转载于:https://www.cnblogs.com/xyzyj/p/6184709.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值