通常在接口中设置常量,并且该常量不能被修改。因为在接口中定义常量时,该常量被修饰为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()方法时,任意传递的参数,编译器就会报错,因为这个方法只接受枚举类型的常量作为其参数。