Java类-枚举类(enum)

枚举类是在很多时候对象都是固定的,实例有限,因而将其封装起来,有这样一段代码。

class Season{
	public static final Season SPRING = new Season("春天","这是春天");
	public static final Season SUMMER = new Season("夏天","这是夏天");
	public static final Season AUTUMN = new Season("秋天","这是秋天");
	public static final Season WINTER = new Season("冬天","这是冬天");
	private String name;
	private String desc;
	private Season(String name,String desc)
	{
		this.name = name;
		this.desc = desc;
	}
	public static Season getSeason(int id)
	{
		switch(id)
		{
			case 1:return SPRING;
			case 2:return SUMMER;
			case 3:return AUTUMN;
			case 4:return WINTER;
		};
		return null;
	}
	public String getName()
	{
		return this.name;
	}
	public String getDesc()
	{
		return this.desc;
	}
}
public class TestEnum{
	public static void main(String[] args)
	{
		System.out.println(Season.getSeason(1).getName());
		System.out.println(Season.SPRING.getName());

	}
}

其运行结果为

春天
春天

一般常用main函数中的Season.SPRING.getName()

当然现在Java都提供了enum专门的枚举类,暂时用不到,用到再写。

About: happyhls


发表评论

电子邮件地址不会被公开。 必填项已用*标注