枚举类型

来源:互联网 发布:创建数据表的sql语句 编辑:程序博客网 时间:2024/06/16 05:09

0、个人对枚举的理解:enum也是类,是继承Enum的final类,其中的元素是实例,是enum实例,是类就会有够造函数,成员变量,成员方法等。

1、枚举类型可以取代以往定义常量的方式,同时枚举类型还赋予了程序在编译时进行检查的功能。

2、以往设置常量,通常将常量放置在接口中,这样在程序中就可以直接使用,并且该常量不能被修改,因为在接口定义中定义常量时,该常量的修饰符为final与static。

3、java中接口的成员变量必须是public final static修饰的,就是不加这些修饰符,也不会报错,因为编译器会为我们自动加上。

接口的所有成员都应该公开,所以是 public

接口不能实例化,所以只有静态成员: static
接口的成员一定应该是常量,所以是 final。

4、枚举类型还赋予了程序在编译时进行检查的功能:

interface Constants { // 将常量放置在接口中public static final int Constants_A = 1;public static final int Constants_B = 12;}public class ConstantsTest {enum Constants2 { // 将常量放置在枚举类型中Constants_A, Constants_B}// 使用接口定义常量public static void doit(int c) { // 定义一个方法,这里的参数为int型switch (c) { // 根据常量的值做不同操作case Constants.Constants_A:System.out.println("doit() Constants_A");break;case Constants.Constants_B:System.out.println("doit() Constants_B");break;}}// 定义一个方法,这里的参数为枚举类型对象public static void doit2(Constants2 c) { switch (c) { // 根据枚举类型对象做不同操作case Constants_A:System.out.println("doit2() Constants_A");break;case Constants_B:System.out.println("doit2() Constants_B");break;}}public static void main(String[] args) {ConstantsTest.doit(Constants.Constants_A); // 使用接口中定义的常量ConstantsTest.doit2(Constants2.Constants_A); // 使用枚举类型中的常量ConstantsTest.doit2(Constants2.Constants_B); // 使用枚举类型中的常量ConstantsTest.doit(3);ConstantsTest.doit2(3);}}
代码中的最后ConstantsTest.doit2(3);不能通过编译,因为doit2()的形参类型是枚举,但是doit(3);没问题,因为3也是常量嘛!!

5、当定义一个枚举类型时,每个枚举类型成员都可以看做是枚举类型的一个实例,这些枚举类型成员都默认被final、public、static修饰这一点和interface很相似),所以当使用枚举类型成员时可直接使用枚举类型名称调用枚举类型成员即可。

6、枚举元素列表必须写在枚举类的最前面,每个元素之间用逗号隔开,元素列表结束位置,若没有其他内容,则可以不写分号,若有其他内容(构造函数,其他的成员变量、成员函数)必须写分号;

7、

a.compareTo(E o) : 比较枚举元素的顺序 
        b.equals(Object obj) : 判断枚举元素是否相同 
        c. name() :  获取元素定义时的名称 
        d.ordinal() : 获取枚举元素被定义时的顺序,从0开始计算 
   注:对于枚举可以使用"=="来比较两个枚举元素相同与否,由于他们已经自动了equals()和hashCode()两个方法, 
        故这两个方法不需要重写。 
8、enum的构造函数(如果重写构造函数的话,必须定义为private类型的,如果构造函数前面没有任何权限修饰符的话,编译也不会出错,因为编译器会添加private,但是你要是写public,编译就会报错。)
9、由于enum的构造函数时private的,任何对象的建立都需要构造函数,因此enum不能在enum的外部实例化,实际上在
public enum Constants{
CONSTANTS_A,
CONSTANTS_B,
CONSTANTS_C
}中的元素都是constants的实例。
Constants niniConstants2 = new Constants();这样写就有问题,但是Constants niniConstants2 = Constants.CONSTANTS_A.就没问题,不解啊!



0 0