Java Enum as Class
In this chapter you will learn:
- How to use enum as Class
- Restrictions for enum class type
- Example - Enum with constructor
- Example - Member methods
Description
You can give constructors, add instance variables and methods, and implement interfaces for enum types.
When you define a constructor for an enum, the constructor is called when each enumeration constant is created.
Each enumeration constant has its own copy of any instance variables defined by the enumeration.
Restrictions
Two restrictions that apply to enumerations.
- an enumeration can't inherit another class.
- an enum cannot be a superclass.
Example 1
Enum with constructor
enum Direction {/*w w w . ja v a 2 s .c o m*/
South(10), East(9), North(12), West(8);
private int myValue;
Direction(int p) {
myValue = p;
}
int getMyValue() {
return myValue;
}
}
public class Main {
public static void main(String args[]) {
System.out.println(Direction.East.getMyValue());
for (Direction a : Direction.values())
System.out.println(a + " costs " + a.getMyValue());
}
}
The code above generates the following result.
Example 2
You can add fields, constructors, and methods to an enum. You can have the enum implement interfaces.
//from www . j a v a2s . c om
enum Coin {
PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
private final int denomValue;
Coin(int denomValue) {
this.denomValue = denomValue;
}
int denomValue() {
return denomValue;
}
int toDenomination(int numPennies) {
return numPennies / denomValue;
}
}
public class Main {
public static void main(String[] args) {
int numPennies = 1;
int numQuarters = Coin.QUARTER.toDenomination(numPennies);
System.out.println(numQuarters);
for (Coin c:Coin.values()) {
System.out.println(c.denomValue());
}
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- enum type Inheriting Enum
- Ordinal value
- Example - Enum Ordinal value
- Example - Overriding toString() to return a Token constant's value