自己实现枚举类

自己实现枚举类

  • A:枚举概述
    • 是指将变量的值一一列出来,变量的值只限于列举出来的值的范围内。举例:一周只有7天,一年只有12个月等。
  • B:回想单例设计模式:单例类是一个类只有一个实例
    • 那么多例类就是一个类有多个实例,但不是无限个数的实例,而是有限个数的实例。这才能是枚举类。
  • C:案例演示
    • 自己实现枚举类
package com.heima.enums;

public class Week01 {
	public static final Week01 MON = new Week01();
	public static final Week01 TUE = new Week01();
	public static final Week01 WED = new Week01();

	//私有构造,不让其他类创建本类对象
	private Week01() {
	}
}
========================================================
package com.heima.enums;

public class Week02 {
	public static final Week02 MON = new Week02("星期一");
	public static final Week02 TUE = new Week02("星期二");
	public static final Week02 WED = new Week02("星期三");
	private String name;

	private Week02(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
}
========================================================
package com.heima.enums;

public abstract class Week03 {

	// 父类引用指向子类对象,匿名内部类
	public static final Week03 MON = new Week03("星期一") {
		public void show() {
			System.out.println("星期一");
		}
	};

	public static final Week03 TUE = new Week03("星期二") {
		public void show() {
			System.out.println("星期二");
		}
	};

	public static final Week03 WED = new Week03("星期三") {
		public void show() {
			System.out.println("星期三");
		}
	};

	private String name;

	private Week03(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public abstract void show();
}
========================================================
package com.heima.enums;

public class Demo01_Enum {
	public static void main(String[] args) {
		Week01 MON = Week01.MON;
		System.out.println(MON);
		
		Week02 TUE = Week02.TUE;
		System.out.println(TUE.getName());
		
		Week03 WED = Week03.WED;
		WED.show();
	}
}

你可能感兴趣的:(JDK5新特性)