java列舉型別

biubiubiuo發表於2018-02-24

public enum Color{
  RED,BLUE,BLACK,YELLOWGREEN
}
  1.enum很像特殊的class,實際上enum宣告定義的型別就是一個類
  2.這些類都是類庫中Enum類的子類(java.lang.Enum<E>),它們繼承了Enum中許多有用的方法
~ 列舉值都是public static final的,也就是常量,因此列舉類中的列舉值都應全部大寫
~ 列舉型別是class,在列舉型別中有構造器,方法和欄位.
~ 但列舉的構造器有很大的不同:
  1.構造器只能在構造列舉值的時候被呼叫
  2.構造器私有private,不允許有public構造器
~ 列舉可以在switch語句中使用

public class EnumDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(Color.BLUE);
		Color[] colors = Color.values();
		for(Color c:colors) {//另一種for迴圈格式:從列舉型別物件colors中依次賦給c
			System.out.println(c);
		}
		
		Person[] person = Person.values();
		for(Person p:person) {
			System.out.println(p);
		}
		
		//***********switch用法****************
		Person a = Person.p3;
		switch(a){
			case p1:
				System.out.println(Person.p1);
				break;
			case p2:
				System.out.println(Person.p2);
				break;
			case p3:
				System.out.println(Person.p3);
				break;
				
		}
	}

}
//當jvm去載入使用列舉類的時候,會預先建立多個列舉型別的物件供外界呼叫
//public static final Color RED = new Color();
//public static final Color BLUE = new Color();
//public static final Color YELLOW = new Color();
enum Color{
	REA,BLUE,YELLOW;//列舉型別的值必須作為第一條語句出現
	private Color(){//構造方法
		System.out.println("構造方法");//有幾個列舉值呼叫幾次
	}
}

//public static final Person p1 = new Person("張三",26);
//public static final Person p2 = new Person("李四",23);
//public static final Person p3 = new Person("王五",22);
enum Person{
	p1("張三",26),p2("李四",23),p3("王五",22);
	private String name;
	private int age;
	private Person(String name,int age) {
		this.name = name;
		this.age = age;
	} 
	public String toString() {
		return name+age;
	}
}

  

相關文章