Enumeration class, java enumeration class

Source: Internet
Author: User

Enumeration class, java enumeration class

This type of instance has limited and fixed classes, which are called enumeration classes in Java. For example, the seasonal class has only four objects, and the planetary class currently has only eight objects.

5.9.1 manual Implementation of enumeration classes
public static final int SEASON_SPRING = 1;public static final int SEASON_SUMMER = 2;public static final int SEASON_FALL = 3;public static final int SEASON_WINTER = 4;

There are several problems: (simple expression)
1. Insecure type: the actual season is an int integer.
2. No namespace:
3. The meaning of the print output is unclear: 1 it is difficult to guess that it represents spring.

5.9.2 enumeration class

Java 5 adds an enum keyword (similar to the class and interface keywords) to define enumeration classes.
An enumeration class is a special class that has its own member variables and methods. It can implement one or more interfaces or define its own constructor.
However, enumeration classes are simple differences from common classes:

  • An enumeration class can implement one or more interfaces. The enum-defined enumeration class inherits the java. lang. Enum class by default, rather than the Object class by default.Cannot inherit other parent classes explicitly. The java. lang. Enum class implements java. lang. Serializable and java. lang. Comparable interfaces.
  • Use Enum to define non-abstract enumeration classesThe final modifier is used by default., So the subclass cannot be derived.
  • The constructor of the enumeration class can only use private. If the constructor's access control character is omitted, private is used by default,
  • All instances of the enumeration class must be explicitly listed in the first line of the enumeration class. Otherwise, this enumeration class will never produce instances. When listing these instances, the system automatically adds the public staic final modifier and does not need to be explicitly added.
    The enumeration class provides a values () method by default, which can easily traverse all enumeration classes.
Package code; public enum SeasonEnum {// list four enumeration class instances in the first row: SPRING, SUMMER, FALL, WINTER ;}

EnumTest. java

Package code; public class EnumTest {public void judge (SeasonEnum e) {// The expression in the switch statement can be an enumeration class switch (e) {case SPRING: System. out. println ("Spring blossom"); break; case SUMMER: System. out. println ("Summer"); break; case FALL: System. out. println ("Autumn"); break; case WINTER: System. out. println ("winter snow"); break;} public static void main (String [] args) {// The enumeration class has a values () method by default, returns all instances of this enumeration class for (SeasonEnum s: SeasonEnum. values () {System. out. println (s);} // when enumeration classes are used, you can use EnumClass. variable to access new EnumTest (). judge (SeasonEnum. SPRING );}}

The java. lang. Enum class provides the following methods, which can be directly used by all enumeration classes:

  • Int compareTo (E o): This method is used to compare the sequence of specified enumerated objects. The same enumeration instance can only be compared with the same enumeration instance type, if the enumerated object is located after the specified enumerated object, a positive integer is returned. If the enumerated object is located before the specified enumerated object, a negative integer is returned. Otherwise, zero is returned.
  • String name (): returns the name of this enumeration instance. This name is one of all enumeration classes listed when the enumeration class is defined, but the toString () method is used in most cases.
  • Int ordinal (): returns the index value of the enumerated value in the enumeration class.
  • String toString (): returns the name of the enumerated constant. Similar to the name method, the toString method is more commonly used.
  • Public static
5.9.3 enumeration class member variables, methods, and constructors

Gender. java

package code;public enum Gender{    MALE,FEMALE;    public String name;}

GenderTest. java

Package code; public class GenderTest {public static void main (String [] args) {Gender g = Enum. valueOf (Gender. class, "FEMALE"); g. name = "female"; System. out. println (g + "stands for:" + g. name );}}

Java should design all classes into well-encapsulated classes, so direct access to the name member variable of the Gender Class should not be allowed, but access to the name should be controlled through methods.
The following code is the improved design.
Gender. java

Package code; public enum Gender {MALE, FEMALE; private String name; public void setName (String name) {switch (this) {case MALE: if (name. equals ("male") {this. name = name;} else {System. out. println ("parameter error");} break; case FEMALE: if (name. equals ("female") {this. name = name;} else {System. out. println ("parameter error") ;}break ;}public String getName () {return this. name ;}}

GenderTest. java

Package code; public class GenderTest {public static void main (String [] args) {Gender g = Enum. valueOf (Gender. class, "FEMALE"); g. setName ("female"); System. out. println (g + "stands for:" + g. name (); g. setName ("male"); System. out. println (g + "stands for:" + g. getName ());}}

FEMALE representative: FEMALE
Parameter Error
FEMALE representative

In fact, this practice is still not good. Enumeration classes should usually be designedImmutable classThat is to say, its member variable value should not be allowed to be changed, which is safer and the code is more concise. Therefore, we recommend that you use private final to modify all member variables of the enumeration class.
If you use the final modifier to modify all member variables, you must specify the initial values for these member variables in the constructor (or specify the default values when defining member variables, you can also specify the initial value in the initialization block, but these two conditions are not common). Therefore, you should explicitly define a constructor with parameters for the enumeration class.
Once a constructor with parameters is explicitly defined for the enumeration class, parameters must be input when listing the enumerated values.

Package code; public enum Gender {MALE ("MALE"), FEMALE ("FEMALE"); private final String name; private Gender (String name) {this. name = name;} public String getName () {return this. name ;}

After a Gender (String name) constructor is created for the Gender enumeration class, the enumerated classes listed are from MALE ("MALE"), FEMALE ("FEMALE "); this code is complete, that is, when enumeration classes are listed in the enumeration classes, the constructor is called to create enumeration class objects. You do not need to use the new keyword or call the constructor explicitly.
Equivalent to the following two codes:

Public static final Gender MALE = new Gender ("MALE"); public static final Gender FEMALE = new Gender ("FEMALE ");
5.9.4 enumeration class for interface implementation

An enumeration class can implement one or more interfaces like a common class.

Package code; public enum Gender2 implements GenderDesc {MALE ("MALE"), FEMALE ("FEMALE"); private final String name; private Gender (String name) {this. name = name;} public String getName () {return this. name;} public void info () {System. out. println ("this is an enumeration class for defining gender ");}}

The enumerated class implementation interface is exactly the same as the ordinary class implementation interface.
If an enumeration class is used to implement methods in an interface, each enumeration value has the same behavior when calling this method (because the method body is identical) if you want each enumeration value to display different behavior modes when calling this method, you can enable each enumeration value to implement this method separately. Each enumeration value provides different implementation methods, so that different enumerated values call this method with different behavior methods.
Example:

Package code; public enum Gender2 implements GenderDesc {MALE ("MALE") {public void info () {System. out. println ("this enumeration value represents male") ;}}, FEMALE ("FEMALE") {public void info () {System. out. println ("this enumeration value represents female") ;}}; private final String name; private Gender2 (String name) {this. name = name;} public String getName () {return this. name;}/* public void info () {System. out. println ("this is an enumeration class used to define gender ");}*/}

In the above Code, the curly braces behind MALE and FEMALE are actually a class body, similar to anonymous internal classes. In this case, when the MALE and FEMALE enumeration values are created, instead of directly creating the Gender enumeration class instance, it is equivalent to creating the Gender anonymous subclass instance. Therefore, only anonymous internal sub-classes of enumeration classes are enclosed in brackets.

Not all enumeration classes use final modification. Non-abstract enumeration classes use final modification by default. For an abstract enumeration class, as long as it contains abstract methods, this is an abstract enumeration class. The abstract modifier is used by default.

5.9.5 enumeration classes containing Abstract METHODS
package code;public enum Operation{    PLUS{        public double eval(double a ,double b){            return (a+b);        }    },    MINUS{        public double eval(double a ,double b){                return (a-b);            }    },    TIMES{        public double eval(double a ,double b){            return (a*b);        }    },    DIVIDE{        public double eval(double a ,double b){            return (a/b);        }    };    public abstract double eval(double a,double b);    public static void main(String [] args){        System.out.println(Operation.PLUS.eval(3,4));        System.out.println(Operation.MINUS.eval(3,4));        System.out.println(Operation.TIMES.eval(3,4));        System.out.println(Operation.DIVIDE.eval(3,4));    }}

7.0
-1.0
12.0
0.75

When defining abstract methods in enumeration classes, you cannot use the abstract keyword to define enumeration classes as abstract classes (because the system automatically adds abstract keywords to them ), however, because the enumeration class needs to be explicitly created, rather than as the parent class, it must be implemented for the abstract method when defining each enumeration value. Otherwise, an error occurs.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.