Java中Enum的使用

package com.zoer.src;

public enum WeekDay {
	Mon_("Monday"), Tue_("Tuesday"), Wed_("Wednesday"), Thu_("Thursday"), Fri_(
			"Friday"), Sat_("Saturday"), Sun_("Sunday");

	private final String day;

	private WeekDay(String day) {
		System.out.println(day);
		this.day = day;
	}

	public static void printDay(int i) {
		switch (i) {
		case 1:
			System.out.println(WeekDay.Mon_);
			break;
		case 2:
			System.out.println(WeekDay.Tue_);
			break;
		case 3:
			System.out.println(WeekDay.Wed_);
			break;
		case 4:
			System.out.println(WeekDay.Thu_);
			break;
		case 5:
			System.out.println(WeekDay.Fri_);
			break;
		case 6:
			System.out.println(WeekDay.Sat_);
			break;
		case 7:
			System.out.println(WeekDay.Sun_);
			break;
		default:
			System.out.println("wrong number!");
		}
	}

	public String getDay() {
		return day;
	}
}

上面的代码中生明了一个enum,枚举类型用来表示一组相同类型的常量。

代码中使用了private的构造函数【enum仅允许private的构造函数】。

Tue_("Tuesday"),括号内的内容就是构造函数中的参数,比如传入Tuesday,则经过构造函数执行之后,Tue的day值就是Tuesday了。

ps:整个enum初始化的过程中,生明了几个值,则构造函数需要执行相应次数。

package com.zoer.src;

public class T {

	/**
	 * @param args
	 */
	public static void main(String args[]) {
		for (int i = 0; i < WeekDay.values().length; i++) {
			WeekDay d = WeekDay.values()[i];
			p(d);
		}
	}

	public static void p(WeekDay d) {
		System.out.println(d + "->" + d.getDay());
	}
}
输出:

Mon_->Monday
Tue_->Tuesday
Wed_->Wednesday
Thu_->Thursday
Fri_->Friday
Sat_->Saturday
Sun_->Sunday


你可能感兴趣的:(java,String,Class,sun)