Sub topic 3
Giving Enum Constants Data and Behavior
So far, each enum constant has been just a name. Often a constant also has information attached to it. A coin has a value in cents. A planet has a mass. In Java, you can store that information inside the enum itself.
Why Attach Data to Constants?
Picture a program that needs the value of each coin. Without enum data, you might write a separate method with a long switch that maps PENNY to 1, NICKEL to 5, and so on. Every new coin then means editing that method. If you forget, you get a bug.
It is simpler to keep each value right next to its constant. Then a coin always knows its own value.
Fields and Constructors in an Enum
A field is a variable that belongs to an object. A constructor is special code that runs when an object is created and sets up its fields. An enum can have both.
enum Coin {
PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
private final int cents;
Coin(int cents) {
this.cents = cents;
}
public int cents() {
return cents;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Coin.DIME.cents()); // 10
int total = 0;
for (Coin c : Coin.values()) {
total += c.cents();
}
System.out.println(total); // 41
}
}Here is what each part does:
PENNY(1)creates thePENNYconstant and passes1to the constructor.- The semicolon after
QUARTER(25)ends the list of constants. You need it whenever more code follows. private final int cents;is the field.finalmeans the value cannot change after it is set.Coin(int cents)is the constructor. It copies the value into the field.cents()is a method, a named block of code you can call. It returns the stored value.
Java calls the constructor once for each constant, the first time the program uses the enum. After that, the four objects already exist and are reused.
Rules for Enum Constructors
Enum constructors follow some rules that class constructors don't:
| Rule | What it means |
|---|---|
| Constants come first | The list of constants must be the first thing inside the enum. |
| Constructor is private | You can leave out `private`, but the constructor is private anyway. |
| No `new` | Writing `new Coin(50)` is a compile error. Only the listed constants exist. |
Adding Methods That Do Work
Methods can do more than return a field. They can compute an answer from it.
enum Size {
SMALL(8), MEDIUM(12), LARGE(16);
private final int ounces;
Size(int ounces) {
this.ounces = ounces;
}
public int ounces() {
return ounces;
}
public boolean isBiggerThan(Size other) {
return this.ounces > other.ounces;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Size.LARGE.isBiggerThan(Size.SMALL)); // true
System.out.println(Size.SMALL.ounces()); // 8
}
}The isBiggerThan method compares the field values. It does not use ordinal(), which only tells you the position in the list. If someone reorders the constants, ordinal() changes but the ounces do not. Store meaning in fields, not in position.
Exercises
Exercise
Write an enum Planet with constants MERCURY, EARTH, and MARS. Give each one a double field for gravity compared to Earth (0.38, 1.0, 0.38), and add a method weightOn(double earthWeight) that returns the weight on that planet.
Show answer
enum Planet { MERCURY(0.38), EARTH(1.0), MARS(0.38); private final double gravity; Planet(double gravity) { this.gravity = gravity; } public double weightOn(double earthWeight) { return earthWeight * gravity; } }. For example, Planet.MARS.weightOn(100) returns about 38.0 (the exact printed value may show a tiny floating-point difference).
Exercise
Why does new Coin(50) fail to compile?
Show answer
Enum constructors are always private, so code outside the enum cannot call them. Only the constants listed in the enum can exist.