10.4 Enumeration

java beginning no concept of enumeration, so developers have to use multiple design pattern instead of the enumeration. jdk1.5 Enumeration

10.4.1 enumeration class that defines

Keywords: enum, use this keyword to realize enumeration type definition, can simplify the use of enumeration define multiple design pattern
Example: Defining enumerated type

public enum Color235 {
       RED,GREEN,BLUE;
}

public class Java235A {
	public static void main(String[] args) {
		Color235 d=Color235.RED;
		System.out.println(d);
	}
}

Results of the:RED

Direct use Enumeration object names to call
Note: The definition of an enumeration names
on the programs, all object names enumeration class definitions used in all capital letters, which is in line with the requirements of multi-design pattern, while the enumeration the Chinese name of the object in the form can also be used to define
example: the use of Chinese definition of enumeration object name

public enum ColorChinese {
      红色,绿色,蓝色;
}

public class JavaChinese {
       public static void main(String[] args) {
		ColorChinese c=ColorChinese.红色;
		System.out.println(c);
	}
}

Results of the

红色

Directly using the class name. Chinese characters. Enumerate the most important feature is the ability to simplify the structure of multi-design pattern

In addition to simplifying the multi enumeration design pattern outside, but also provides a convenient information acquiring operation by the enumeration class .values ** () ** configuration can obtain all objects in the form of enumeration array of objects.
All contents of the output enumeration: Example

public enum Color235B {
       javase,javaweb,数据结构,框架;
}

public class Java235B {
       public static void main(String[] args) {
		 for(Color235B c:Color235B.values()) {
			 System.out.print(c+"、");
		 }
	}
}

Results of the:

javase、javaweb、数据结构、框架、

This procedure using values ​​() method to get all the enumeration object Color235B subsequently acquired using foreach loop for each object and outputs.

Multi-Enumeration been adopted in place of a design pattern is very important reason is that the object can be enumerated type is determined directly in the switch statement.
Example: judge enumerated types in a switch

public enum Color235 {
       RED,GREEN,BLUE;
}

public class Java236 {
       public static void main(String[] args) {
		Color235 c=Color235.RED;
		switch(c) {                  //支持枚举判断
		case RED:                    //匹配内容
			System.out.println("红色");
			break;
		
       case GREEN:                    //匹配内容
			System.out.println("绿色");
			break;
		
       case BLUE:                    //匹配内容
	        System.out.println("蓝色");
	        break;
       }
	}
}

This procedure may be implemented directly in the matching switch enumerated objects, and if multiple design pattern, it can only be matched with the output content determined by a large number of the if statement.

提示:关于switch允许操作的数据类型
JDK1.5之前:只支持Int或Char型数据
JDK1.5之后:增加enum型数据
JDK1.7之后:增加String型数据

10.4.2Enum class

Enumeration is not a new type, he just provides a more convenient structure. Strictly speaking, each defined using the enum class actually belong to a class inherits the parent class Enum, but rather the class is defined as follows java.lang.Enum

public abstract class Enum<E extends Enum<E>>
		extends Object implements Comparable<E>, Serializable {}

It can support the definition of classes in the generic Enum limit, while providing a method as conventional tables Enum class

Method name (Type) Description
protected Enum(String name,int ordinal) (Configuration) of the incoming object and serial number
public final String name() (General) to obtain the object name
public final int ordinal() (Normal) to obtain the object number

Enum class constructor uses protected access, this packaging in fact also belongs to the constructor implemented. At the same time it can be automatically pass an object name and a sequence number for each instance of the enumeration object.
Example: to observe the link between the keyword and enum Enum class

public enum Color235 {
       RED,GREEN,BLUE;
}

public class Java237 {
       public static void main(String[] args) {
		for(Color235 c:Color235.values()) {
			System.out.println(c.ordinal()+"-"+c.name());
		}
	}
}

Program results

0-RED
1-GREEN
2-BLUE

In this program are invoked every output of a class object enumeration ORDINAL () and name () methods defined in the class Enum to obtain the corresponding information, can be demonstrated, enum defined Enum enumeration class inherit the default class.

10.4.3 defined enumeration structure

Enumeration member properties, constructors, ordinary methods can also be defined. But the design pattern is a multi enumeration essence, the method does not allow public construction defined. If the class does not provide no constructor parameters, you must explicitly pass parameters when defining the content of each enumeration object.
Example: Defining member properties and methods in the enumeration class

public enum Color237 {                    //枚举类
       RED("红色"),GREEN("绿色"),BLUE("蓝色");//枚举对象要写在首行
	   private String title;               //成员属性
	   private Color237(String title) {          //构造方法初始化属性
		   this.title=title;
	   }
	   @Override
	   public String toString() {
		   return this.title;
	   }
}


public class Java238A {
      public static void main(String[] args) {
		for(Color237 c:Color237.values()) {
			System.out.println(c.ordinal()+"-"+c.name()+"-"+c);
		}
	}
} 

Results of the

0-RED-红色
1-GREEN-绿色
2-BLUE-蓝色

Structure is defined in the configuration of the enumeration method and overrides toString () method of the Object class, it can be found enumerated functional structure has been expanded in java, so that the class structure closer.
Example: enum class that implements the interface by

public interface IMessage {
       public String getMessage();
}


public enum Color238 implements IMessage {  //枚举类实现接口
	RED("红色"),GREEN("绿色"),BLUE("蓝色");      //枚举对象要写在首行
	private String title;                 //成员属性
	private Color238(String title) {      //构造方法初始化属性
		this.title=title;
	}

	@Override
	public String getMessage() {        //方法覆写
		
		return this.title;
	}
        
}

public class Java238 {
        public static void main(String[] args) {
			IMessage msg=Color238.BLUE;
			System.out.println(msg.getMessage());
		}
}

Results of the

蓝色

This program lets enumerate implements IMessage interface, so you need to override the abstract methods interface in the enumeration class, because Color238 IMessage interface is a subclass, so every enumeration class object can transition through up implementation of the object IMessage interface object is instantiated.

There enumeration is a special function can be defined directly abstract method, then you can abstract methods are implemented in this enumeration each object.
Example: Defining an abstract method in the enumeration

package com.lxh.tenchapter;

public enum Color239 {
       RED("红色"){
    	   @Override
    	   public String getMessage() {    //覆写抽象方法
    		   return "【RED】"+this;
    	   }
       },GREEN("绿色"){
    	   @Override
    	   public String getMessage() {
    		   return "【RREEN】"+this;
    	   }
       },BLUE("蓝色"){
    	   @Override
    	   public String getMessage() {
    		   return "【BLUE】"+this;
    	   }
       };
	private String title;
	private Color239(String title) {
		this.title=title;
	}
	public String toString() {      //输出对象信息
		return this.title;
	}
	public abstract String getMessage();    //直接定义抽象方法 
}


public class Java239 {
       public static void main(String[] args) {
		System.out.println(Color239.BLUE.getMessage());
	}
}

Results of the

【BLUE】蓝色

This procedure using the abstract keyword defines an abstract method in the enumeration, so it is necessary to override this abstract methods are enumerated in each class object.

10.4.4 Enumeration Applications

Enumeration is the definition of the range of the object instance, and can be used as a member of the type enumerated attribute type. For example, the definition of a Person class now, which need to provide gender attributes, and gender do not want the user to easily enter, so the use of the most appropriate enumeration.
Example: Enumeration structural applications

public enum Sex {
       NAM("男"),WOMAN("女");
       private String title;
       private Sex(String title) {
    	   this.title=title;
       }
       public String toString() {   //获取对象信息
    	   return this.title;
       }
}


public class Person {
       private String name;
       private int age;
       private Sex sex;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Sex getSex() {
		return sex;
	}
	public void setSex(Sex sex) {
		this.sex = sex;
	}
	public Person(String name, int age, Sex sex) {
		this.name = name;
		this.age = age;
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "Person [姓名=" + name + ", 年龄=" + age + ", 性别=" + sex + "]";
	}
       
	
}


public class Java240 {
       public static void main(String[] args) {
		Person per=new Person("李明",20,Sex.NAM);
		System.out.println(per);
	}
}

Results of the

Person [姓名=李明, 年龄=20, 性别=男]

When using this procedure enumerated type defined Person class, when instantiated Person class objects can be defined in the range Sex object.

Published 162 original articles · won praise 9 · views 3096

Guess you like

Origin blog.csdn.net/ll_j_21/article/details/104682123