Java Review (XVII object-oriented ---- enumeration class)


enum is called the enumeration, a new feature introduced in JDK 1.5.
In Java, the modified enum keyword type is an enumerated type.


Enum class entry

Java 5 added a key enum Yu (it class, same status interface keywords) to define enumeration class. Enumeration class is a special type, as it can have its own fields, methods, may implement one or more interfaces can define your own constructor. A Java source file can define a maximum of enumeration class a public access, and the Java source files and class name must also be the same as the enumeration class.

It has the following simple difference between ordinary class.

  • Enumeration class may implement one or more interfaces using enum defined java.lang.Enum enumeration class inherits default class, Object class inheritance instead of the default, and therefore can not be explicitly enumerated classes inherit other parent. Wherein java.lang.Enum java.lang.Serializable class implements two interfaces and java.lang.Comparable.
  • Use enum definition, non-abstract class enumeration is used by default final modification, so enumeration class can not be subclassed.
  • Enumeration class constructor can use private access specifier, if access specifier is omitted constructors, use the private modifier default; if the specified mandatory access control at only specify private modifiers.
  • Enumerate all instances of the class must be explicitly listed in the first line of an enumeration type, or enumeration type can never produce instances. When listing these instances, the system will automatically add public static final modification, without the programmer explicitly added. Enumeration class valuesO provides a default method that can easily traverse all the enumerated value.

The following program defines a SeasonEnum enumeration class.


SeasonEnum.java

public enum SeasonEnum {
	//在第一行列出 4 个枚举实例
	SPRING, SUMMER ,FALL,WINTER ;
}

When enumeration class definitions, explicit need to list all the enumerated values, such as, SUMMER, FALL, shown above SPRING WINTER, among all the enumerated values ​​comma separated, after the end of the enumeration values ​​include semicolons as the end. These values ​​represent the enumeration of all possible instances of the enumeration class.

If you need to use an instance of the enumeration class, you can use the form EnumClass.variable, such as SeasonEnum. SPRING.


EnumTest.java

public class EnumTest {
	public void judge(SeasonEnum s) {
	  // switch 语句里的表达式可以是枚举值
	  switch (s) {
	    case SPRING:
	      System.out . println( " 春暖花开,正好踏青") ;
	      break ;
	    case SUMMER :
	      System . out.println( " 夏日炎炎,适合游泳 " ) ;
	      break;
	    case FALL:
	     System.out.println( " 秋高气爽 , 进补及时 " ) ;
	     break;
	    case WINTER:
	     System . out.println( " 冬日雪飘,国炉赏雪 " );
	     break;
	  }
	}  
	
	public static void main(String[] args){
	 //枚举类默认有一个 values ()方法,返回该枚举类的所有实例
	  for (SeasonEnum s : SeasonEnum.values()) {
	    System.out.println(s) ;
	  }
	  //使用枚举实例时,可通过 EnumClass . variable 形式来访问
	  new EnumTest().judge(SeasonEnum.SPRING) ;
	}

}

All of the enumeration classes inherit the java.lang.Enum class, enum class can use java .lang.Enum class contained directly. . Java lang .Enum class provides the following several methods:

Here Insert Picture Description


The enumeration class member variables, methods and constructors

Enumeration class is also a class, but it is a special category, so it can be defined as member variables, methods and constructors.

The following procedures define a Gender enumeration class, which contains an enumeration class instance variable name.

Gender.java

public enum Gender {
	MALE , FEMALE;
	//定义一个 public 修饰的实例变量
	public String name;
}

This enumeration class is used by the following procedure.

GenderTest.java

public class GenderTest {
	public static void main(String[] args) {
		//通过 Enum 的 valueOf ()方法来获取指定枚举类的枚举值
		Gender g = Enum.valueOf(Gender.class , "FEMALE");
		//直接为枚举值的 name 实例变量赋傻
		g.name = "女";
		//直接访问枚举值的问me 实例变量
		System.out.println(g + "代表 :" + g.name);
	}

}

As mentioned earlier, Java classes should be designed to be good for all classes of the package, it should not be allowed to directly access the member variable name Gender class, but should be controlled by the method of access to the name. It may appear very confusing situation, such as the above program just set g.name = "female", if using g.name = "male", and that the program will be very confusing, FEMALE male representatives situation that may arise. The following code can be improved by designing Gender class.

Gender.java

public enum Gender {
	MALE , FEMALE ;
	//私有化,免其他程序直接访问该 name 成员变量
	private String name ;
	public void setName(String name){
	 switch (this){
	  case MALE :
	   //MALE 枚举值的 name 变量则只能设置为"男 "
	   if (name.equals("男")) {
	     this.name = name;
	   }else{
	     System . out . println("参数错误") ;
	     return;
	   }  
	  break ;
	  case FEMALE:
	   // FEMALE 枚举值的 name 变量只能设置为"女" 
	   if (name.equals("女") ) {
	    this.name = name;
	   }else {
	    System.out.println ("参数错误 ") ;
	    return;
	   } 
	  break;
	 }
	}
	public String getName() {
	 return this.name;
	}
}

Implement enumeration class interface

Enumeration class may also implement one or more interfaces. Implement one or more interfaces with exactly the same general category, enumeration class implements one or more interfaces, the interface contains methods also need to implement. The following program defines a GenderDesc interface.


GenderDesc.java

public interface GenderDesc{
  void info () ;
}  

Defines a infoO GenderDesc interface in the above method, the following Gender enumeration class implements the interface, and implement the info () method contains the interface. The following is Gender enumeration class code.


Gender.java

public enum Gender implements GenderDesc{
	MALE , FEMALE ;
	private String name ;
	public void setName(String name){
	 switch (this){
	  case MALE :
	   if (name.equals("男")) {
	     this.name = name;
	   }else{
	     System . out . println("参数错误") ;
	     return;
	   }  
	  break ;
	  case FEMALE:
	   if (name.equals("女") ) {
	    this.name = name;
	   }else {
	    System.out.println ("参数错误 ") ;
	    return;
	   } 
	  break;
	 }
	}
	public String getName() {
	 return this.name;
	}
	
   //实现接口info()方法
   public void info(){
     System.out.println("这是一个用于定义性别的枚举类 " );
   }  
   
}

Enumeration class and implements the use of the same general category implement an interface, the interface contains abstract methods well realized.

If the interface where the method is implemented by the enumerated classes, each enumeration value when calling the method has the same behavior (because the method body exactly the same).

If you need each enum values ​​exhibit different behavior when a call to this method, you can make each enumeration values ​​to implement this method, each enumeration values ​​provide different implementations, so that different enumeration have behave differently when the value of the method is called. Gender enumerated in the following classes, different values ​​of different enumeration to achieve info () method.


Gender.java

public enum Gender implements GenderDesc{
	//此处的枚举值必须调用对应的构造器来创建
    MALE ("男"){
    //花括号部分实际上是一个类体部分
    //并不是直接创建Gendar枚举类的实例
    //而是相当于创建 Gender 的匿名子类的实例
      public void info(){
        System.out.println("这个枚举值代表男性") ;
      } 
     }  
    
   FEMALE(" 女"){
     public void info(){
       System.out.println("这个枚举值代表女性") ;
     }
   }  
   
	private String name ;
	public void setName(String name){
	 switch (this){
	  case MALE :
	   if (name.equals("男")) {
	     this.name = name;
	   }else{
	     System.out.println("参数错误") ;
	     return;
	   }  
	  break ;
	  case FEMALE:
	   if (name.equals("女") ) {
	    this.name = name;
	   }else {
	    System.out.println ("参数错误 ") ;
	    return;
	   } 
	  break;
	 }
	}
	public String getName() {
	 return this.name;
	} 
   
}

Abstract class enumeration method comprising

Suppose there is an Operation enumeration class, its four enumeration value PLUS, MINUS, TIMES, DIVIDE represent the addition, subtraction, multiplication, four kinds of operation in addition to the need to define an enumeration class eval () method to complete the calculation.

Can be seen from the above description, Operation need to PLUS, MINUS, TIMES, DIVIDE four values ​​have different implementations of the eval () method. Operation at this time can be considered as a evalO abstract class defines the enumeration method, and then let the four enumerated values ​​were eval () provides different implementations. For example, the following code.


Operation.java

public enum Operation {
   //定义每个枚举值时实现抽象方法
	PLUS{
	  public double eval(double x , double y) {
	    return x + y;
	  }  
	},	
	MINUS{
	  public double eval(double x , double y) {
	    return x - y;
	  }
	},  	
	TIMES{
	  public double eval(double x , double y) {
		  return x * y;
	  }
	} ,
	DIVIDE{  
	  public double eval(double x , double y) {
	    return x / y;
	  }
	};  
	// 为枚举类定义一个抽象方法
	// 这个抽象方法由不同的枚举值提供不同的实现
	public abstract double eval(double x , double y);
	public static void main(String[] args) {
		System.out.println (Operation.PLUS.eval (3 , 4)) ;
		System.out.println(Operation.MINUS.eval(5,4)) ;
		System.out.println(Operation.TIMES.eval(5,4)) ;
		System.out.println(Operation.DIVIDE.eval(5,4));
	}	

}

The above program compiler generates class files 5, wherein a class file corresponding to Operation, its four sub anonymous inner classes, each corresponding to a respective class file.

Enum class can not be used when defining an abstract method abstract keyword enum class is defined as an abstract class (abstract because the system automatically adds the key to Yu for it), but because of the need to explicitly create an enumeration type enum values, rather than as parent, must provide an implementation for abstract methods defining each enumeration value, otherwise the compilation error will occur.



reference:

[1]: "crazy Java handouts"
[2]: https: //juejin.im/post/5c13133be51d456fac740c98

Published 136 original articles · won praise 36 · views 30000 +

Guess you like

Origin blog.csdn.net/sinat_40770656/article/details/102880466