枚举类型中的构造方法

package 枚举类型与泛型;
/*
 * 枚举类型中的构造方法
 * 在枚举类型中,可以定义构造方法,但是规定这个构造方法必须为private修饰符所修饰。
 *
 */
public class EnumIndex_Test {
    public enum Constants2{//将常量放置在枚举类型中
        //定义带参数的枚举类型成员
        Constants_A("我是枚举成员A"),
        Constants_B("我是枚举成员B"),
        Constants_C("我是枚举成员C"),
        Constants_D(3);
        private String description;
        private int i=4;
        
        private Constants2() {
            
        }
        private Constants2(String description) {
            this.description=description;
        }
        private Constants2(int i) {
            this.i=this.i+i;
        }
        public String getDescription() {
            return description;
        }
        public int getI() {
            return i;
        }
    }    
    public static void main(String[] args) {
        for(int i=0;i<Constants2.values().length;i++) {
            System.out.println(Constants2.values()[i]+"调用getDescription()方法为:"+Constants2.values()[i].getDescription());
        }
        System.out.println(Constants2.valueOf("Constants_D")+"调用getI()方法为:"+Constants2.valueOf("Constants_D").getI());
    }

}

运行结果:

Constants_A调用getDescription()方法为:我是枚举成员A
Constants_B调用getDescription()方法为:我是枚举成员B
Constants_C调用getDescription()方法为:我是枚举成员C
Constants_D调用getDescription()方法为:null
Constants_D调用getI()方法为:7


猜你喜欢

转载自blog.csdn.net/qq_41978199/article/details/80697016