2018-05-12
Enumeration
I. Definition of enumerations and characteristics of underlying analysis
JDK1.5 introduces a new data type-enumeration, which is a special class. is a fixed collection of multiple objects.
Define the format:
[Modifier] enum enum class name {
Constant A, constant B, constant C;
}
Our custom enumeration types, at compile (bottom), are directly inherited from the Java.liang.Enum class, and the enum is the parent class for all enumerations.
Features of the enumeration class:
1. The immediate parent class of the enumeration is java.liang.Enum, but the inherited enum cannot be displayed.
2, enumeration is equivalent to a class, you can define construction methods, member variables, ordinary methods and abstract methods.
3, the default private construction method.
4. Each instance is represented by a global constant, the object of the enumeration class is fixed, the number of instances is limited, and cannot be created using new.
5. The enumeration instance must be in the first part of the enumerator, separated by a semicolon and other member variables after enumerating the list of instances.
6. When the instance is enumerated with curly braces, the instance is an object of the anonymous inner class (view the compiled class file).
--------------------------------------------------------------------------------------------------------------- -------
Ii. use of enumerations
1. The enumeration is a global static constant, so it can be called using the enumeration class name.
Weekday day = Weekday.monday;
2. Because the Java.liang.Enum class is the parent class for all enum classes, all enumeration objects can invoke methods in the Enum class.
String NAME = Enumeration object. Name ();//returns the constant name of the enumeration object
int ordinal = enum object. ordinal ();//Returns the ordinal of an enumeration object, starting with 0
3. static methods for compiler-generated enumeration classes
enumeration type [] values ();
weekday[] ws = Weekday.values ();//Returns all constants of the current enumeration type and encapsulates them with an array.
4. Switch also supports Operation enumeration type
The switch statement before JDK1.6 only supports the Int,char,enum type, which is supported because the underlying uses the ordinal of the enumeration object, and the ordinal type is the int type
5. Single-instance design mode of enumeration
Reference:http://softbeta.iteye.com/blog/1185573
Ii. Java Object-oriented (18) _ Enumeration