At present, an enum constant can access the following:
- The state and behavior common to all enum constants
- Overridden methods
For the Size enum (defined in the preceding section), you can access the state and behavior common to all enum constants, as follows:
System.out.println(Size.SMALL.toText()); // toString is defined for all constants
The preceding code will have the following output:
36 X 19
You can also access the behavior that a specific enum constant overrides as follows:
System.out.println(Size.LARGE.toText());
The preceding code will have the following output:
LARGE
However, you can't access the state or behavior that is specific to an enum constant, as shown in the following code:
System.out.println(Size.MEDIUM.number); // Doesn't compile System.out.println(Size.MEDIUM.getSize()); // Doesn't compile
The getSize() method and the number variable can't be accessed by using the MEDIUM constant. That is because MEDIUM creates an anonymous class and overrides the methods of the Size enum. It can't access the constant, specific state or behavior, because it's still referenced by a variable of the Size type. The following figure should help you remember this: