I. Overview
An enum, called enumeration, is a new feature introduced in JDK 1.5 and is housed in a Java.lang package.
creating an enumeration type to use the enum keyword implies that the type created is a subclass of the Java.lang.Enum class (Java.lang.Enum is an abstract class). Enum types conform to common modeClass Enum<E extends Enum<E>>
, whileE
represents the name of an enumeration type. Each value of the enumeration type is mapped to aprotected Enum(String name, int ordinal)
constructor, where the name of each value is converted to a string, and the ordinal setting indicates the order in which this setting was created.
public enum Enumtest {MON, TUE, WED, THU, FRI, SAT, SUN;}
This code actually calls the Enum 7 times (String name, int ordinal):
New Enum<enumtest> ("MON", 0); new enum<enumtest> ("TUE", 1); New enum<enumtest> ("WED", 2); ... ...
Second, custom enumeration property methods
Add the attribute of value and the method of GetValue () to the Enum object, and construct the method overriding the default Isrest method:
Public enum enumtest { mon (1), tue (2), wed (3), THU (4), fri (5), sat (6) { @Override public boolean isrest () { return true; } }, sun (0) { @ Override public boolean isrest () { return true; } }; private int value; private enumtest (Int value) { MON (1) value=1 this.value = value; } public int getvalue () { return value; } public boolean isrest () { return false; }}
The value values here indicate the value in parentheses when the enumeration value is defined, which differs from the value returned by the enumeration ordinal () method, and ordinal gets the subscript ordinal of the value.
Enumeration needs to be noted (see java.lang.Enum source for details):
Enumeration can use the switch branch syntax
The enumeration class can override the default ToString method, and the default ToString returns the name (MON)
Enumeration constants are singleton, so calling the = = Operand class directly is not an option to override the method
Cloning is not allowed because enumeration constants are singleton
three, enumeration and constant differences
Enumerations and constants are used to indicate constants, but there are some differences between them:
1. An enumeration is a data type and is not a constant, that is, you can be an enumeration variable when you define an attribute variable in an entity, but you cannot define a reference variable as a constant (like an enumeration value is a class, and a constant cannot change the value)
2. When generating objects in dynamic reflection, class objects contain, enumerations can be used as normal variables but constants cannot be met, and also in data storage (Hibernate)
3. Constant NO type constraint
Iv. Summary
Enumerations have their own properties, which can be understood as a collection of special classes and the convenience of having constants on display, complementing the drawbacks of constants as attributes of entity objects.
Enum Enum class