What is the difference between an enum type and java.lang.Enum?
An enum type, also called enumeration type, is a type whose fields consist of a fixed set of constants. The purpose of using enum type is to enforce type safety.
While java.lang.Enum is an abstract class, it is the common base class of all Java language enumeration types. The definition of Enum is:
public abstract class Enum>
extends Object
implements Comparable, Serializable
All enum types implicitly extend java.lang.Enum.
The enum is a special reference type, it is not a class by itself, but more like a category of classes that extends from the same base class Enum. Any type declared by the key word "enum" is a different class. They easiest way to declare a enum type is like:
public enum Season {
SPRING, SUMMER, AUTUM, WINTER
}
or
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Here Season and Day are both enum, but they are different type. All the constants in a enum type is of the same type. For example, SPRING and SUMMER are both of type Season.
Since all enum types All enum types implicitly extend java.lang.Enum, all the methods defined in the Enum class are available to all enum types, such as the
String name() method, which returns the name of this enum constant
int ordinal() method, which returns the ordinal of this enumeration constant, starts from 0
For more information, refer to SCJP Study Guide: Enums
Note: Since Java does not support multiple inheritance, an enum cannot extend anything else.
0 comments:
Post a Comment