天天看点

Java自定义枚举类

package com.guaji.exer;

/*	1. 枚举类的理解:类的对象只有有限个,确定的 ,我们称此类为枚举类
	2. 当需要定义一组常量时,强烈建议使用枚举类
	3. 如何枚举类中只有一个对象,那么可以作为单例模式的实现方式
*/
class EnumExer1{
	//枚举类对象的属性不应允许被改动, 所以应该使用 private final 修饰
	private final String SEASONNAME;
	private final String SEASIONDESC;
	//枚举类的使用 private final 修饰的属性应该在构造器中为其赋值
	private EnumExer1(String name ,String desc){
		this.SEASONNAME=name;
		this.SEASIONDESC=desc;
	}
	// 在类的内部创建枚举类的实例。声明为:public static final
	public static final EnumExer1 SPRING=new EnumExer1("春天", "春暖花开");
	public static final EnumExer1 SUMMER=new EnumExer1("夏天", "Hao");
	public static final EnumExer1 AUTUMN=new EnumExer1("秋天", "好");
	@Override
	public String toString() {
		return "EnumExer1 [SEASONNAME=" + SEASONNAME + ", SEASIONDESC=" + SEASIONDESC + "]";
	}
	

}

enum EnumExer2{
	 SPRING("春天", "春暖花开"),
	 SUMMER("夏天", "Hao"),
	 AUTUMN("秋天", "好");	
	//枚举类对象的属性不应允许被改动, 所以应该使用 private final 修饰
	private final String SEASONNAME;
	private final String SEASIONDESC;
	//枚举类的使用 private final 修饰的属性应该在构造器中为其赋值
	private EnumExer2(String name ,String desc){
		this.SEASONNAME=name;
		this.SEASIONDESC=desc;
	}
	public String getSEASONNAME() {
		return SEASONNAME;
	}
	public String getSEASIONDESC() {
		return SEASIONDESC;
	}
	

}

interface  obj{
	void show();
	
}

enum EnumExer3 implements obj{
	 SPRING("春天", "春暖花开"){
		 @Override
		public void show() {
			System.out.println("真好");
			
		}
	 },
	 SUMMER("夏天", "Hao"){
		 @Override
		public void show() {
			 System.out.println("差劲");
			
		}
	 },
	 AUTUMN("秋天", "好"){
		 @Override
		public void show() {
			 System.out.println("真差");
			
		}
	 };	
	//枚举类对象的属性不应允许被改动, 所以应该使用 private final 修饰
	private final String SEASONNAME;
	private final String SEASIONDESC;
	//枚举类的使用 private final 修饰的属性应该在构造器中为其赋值
	private EnumExer3(String name ,String desc){
		this.SEASONNAME=name;
		this.SEASIONDESC=desc;
	}
	public String getSEASONNAME() {
		return SEASONNAME;
	}
	public String getSEASIONDESC() {
		return SEASIONDESC;
	}
	
	

}


/*values()方法:返回枚举类型的对象数组。该方法可以很方便地遍历所有的枚举值。
 	valueOf(String str):可以把一个字符串转为对应的枚举类对象。要求字符串必须是枚举类对象的“名字”。如不是,会有运行时异常:IllegalArgumentException。  
	toString():返回当前枚举类对象常量的名称
*/

public class EnumExer{
			public static void main(String[] args) {
					EnumExer3[] values = EnumExer3.values();
					for (int i = 0; i < values.length; i++) {
						System.out.println(values[i]);
						values[i].show();
					}
					System.out.println("*****************");
					System.out.println(EnumExer2.valueOf("SPRING"));
					System.out.println(EnumExer2.SPRING);
			}
}