Enums are just magic classes to help prevent the methodless-interface antipattern. They let you make classes that will enumerate values, but also keep the types specific. Before, we could simulate enums with a bunch ofstatic final int variables or something. The problem with those is that you could confuse any int with one of the constants. With enumerations, only the values in the enum are valid. For example:
public enum JettStaff {
ADRIAN,
ARIJIT,
BETH,
ERIC,
KATIE,
KATY,
RAJA,
RICH,
SUZANNE
};
JettStaff x = JettStaff.SUZANNE;
Now, it gets even cooler. I don't have to keep track of separate information to store, say the peoples' full names. I can associate them directly, just like in a class! Each of the values of JettStaff are instances of theJettStaff enumeration, so we can define a constructor and a toString() method.
public enum JettStaff {
ADRIAN("Adrian German"),
ARIJIT("Arijit Sengupta"),
BETH("Beth Plale"),
ERIC("Eric Wernert"),
KATIE("Katie A. Siek"),
KATY("Katy Borner"),
RAJA("Raja Sooriamurthi"),
RICH("Rich Kick"),
SUZANNE("Suzanne Menzel");
private String name;
public JettStaff(String n) { this.name = n; }
public String toString() { return this.name; }
}
JettStaff x = JettStaff.SUZANNE;
System.out.println(x);
But wait, it gets cooler! Now you can also give each enumerated value a custom body. Since they're each instances, you could design a toString() method for each:
public enum JettStaff {
ADRIAN("Adrian German") {
public String toString() {
return name + " (dgerman@indiana.edu)";
}
},
ARJIT("Arjit Sengupta") {
public String toString() {
return name + " (asengupt@indiana.edu)";
}
},
// and on for the rest...
private String name;
public JettStaff(String n) { this.name = n; }
}
JettStaff x = JettStaff.SUZANNE;
System.out.println(x);