Enums with fields, constructors and methods
40 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Each enum constant is an object, so it can carry its own data and methods: a Rs. 10 coin knows its value, and an AC 3 Tier ticket knows its code 3A and its fare.
Constants that carry data
An enum with fields is an enum whose constants carry their own data. Each constant passes values in brackets, such as TEN(10), to the enum's constructor, which stores them in that constant's fields.
A piggy-bank app needs the value of each coin. Constants are objects, so each one can keep its value in a field, set once by a constructor.
Example 1 · Coins that know their value
enum Coin { ONE(1), TWO(2), FIVE(5), TEN(10), TWENTY(20);
private final int value;
Coin(int value) { this.value = value; }
int getValue() { return value; }}
public class PiggyBankDemo { public static void main(String[] args) { Coin[] piggyBank = { Coin.TEN, Coin.FIVE, Coin.FIVE, Coin.TWO, Coin.ONE, Coin.TWENTY }; int total = 0; for (Coin coin : piggyBank) { total = total + coin.getValue(); } System.out.println("Coins: " + piggyBank.length); System.out.println("Total: Rs. " + total); System.out.println("A TEN is worth Rs. " + Coin.TEN.getValue()); }}Coins: 6 Total: Rs. 43 A TEN is worth Rs. 10
What this code does
TEN(10)passes10to the constructor, which stores it in thevaluefield of theTENobject. The;afterTWENTY(20)ends the list of constants.- Each constant has its own
value, socoin.getValue()gives the right amount for every coin in the array.
This keeps a constant and its data in one place. Without fields you would need a separate switch for every piece of data, in every place that needs it.
The enum constructor is always private
An enum constructor sets up the fields of each constant. It is always private, whether you write private or nothing, and only Java calls it, once per constant; no code can call it with new.
A teammate makes the Coin constructor public, hoping other classes can create a Rs. 50 coin. javac refuses: the listed constants are the only objects an enum may ever have.
Example 2 · Mistake: a public constructor
enum Coin { ONE(1), TWO(2), FIVE(5);
private final int value;
public Coin(int value) { this.value = value; }}
public class PublicConstructorDemo { public static void main(String[] args) { System.out.println(Coin.FIVE); }}PublicConstructorDemo.java:6: error: modifier public not allowed here
public Coin(int value) {
^
1 errorWhat this code does
- An enum constructor is always private, because only the constants may create objects. Asking for
publicis an error. - Fix: remove
public(or writeprivate). The constructor still runs for every constant.
Example 3 · Mistake: no semicolon after the constants
enum Coin { ONE(1), TWO(2), FIVE(5)
private final int value;
Coin(int value) { this.value = value; }}
public class SemicolonDemo { public static void main(String[] args) { System.out.println(Coin.FIVE); }}SemicolonDemo.java:2: error: ',', '}', or ';' expected
ONE(1), TWO(2), FIVE(5)
^
SemicolonDemo.java:6: error: '.class' expected
Coin(int value) {
^
SemicolonDemo.java:6: error: ',', '}', or ';' expected
Coin(int value) {
^
SemicolonDemo.java:6: error: enum constant expected here
Coin(int value) {
^
4 errorsWhat this code does
- Without
;afterFIVE(5), javac thinks more constants follow and gets confused by the lines after it. Read only the first error: it points just afterFIVE(5). - Fix: add
;after the last constant. The other errors disappear with it.
The shape of an enum with members:
- Constants come first. A field written above them gives
enum constant expected here. - A semicolon ends the list when anything follows the constants.
- The constructor is private: write
privateor nothing;publicorprotectedis an error.
When the constructor runs
The constructor runs once for each constant, in declaration order, the first time the program uses the enum: the same moment a static block (opens in a new tab) runs. After that the constants are reused.
Example 4 · The constructor runs once per constant
enum Spice { MILD("Mild"), MEDIUM("Medium"), HOT("Hot");
private final String label;
Spice(String label) { this.label = label; System.out.println("Creating " + label); }
String getLabel() { return label; }}
public class CreateOnceDemo { public static void main(String[] args) { System.out.println("Menu opened"); Spice a = Spice.HOT; System.out.println("Biryani: " + a.getLabel()); Spice b = Spice.MILD; System.out.println("Paneer: " + b.getLabel()); }}Menu opened Creating Mild Creating Medium Creating Hot Biryani: Hot Paneer: Mild
What this code does
- Nothing is created before
mainfirst touchesSpice. At that moment Java runs the constructor for all three constants, in declaration order. - Using
Spice.MILDlater does not create anything: the three objects already exist and are reused.
Calling values() again, or using a constant a hundred times, never runs the constructor again. One rule follows from this early start: the constructor may not read or change the enum's own static fields, because they are not ready yet. javac reports illegal reference to static field from initializer.
Keep enum fields private final
Every part of the program shares the same Plan.BASIC object. If its price field can change, a discount for one student changes the price for everyone.
Example 5 · Mistake: a field that can change
enum Plan { BASIC(199), PREMIUM(649);
int price;
Plan(int price) { this.price = price; }}
public class SharedPlanDemo { static void bill(String name, Plan plan, boolean student) { if (student) { plan.price = plan.price / 2; } System.out.println(name + " pays Rs. " + plan.price); }
public static void main(String[] args) { bill("Riya", Plan.BASIC, true); bill("Karan", Plan.BASIC, false); }}Riya pays Rs. 99 Karan pays Rs. 99
What this code does
billhalves the price stored inside the one sharedPlan.BASICobject. Karan is not a student, yet he now pays Rs. 99 too.- With
private final int price, the lineplan.price = ...would not compile. Keep the student price in a local variable instead.
Make every enum field private final and add getters. Then a bad line like p.price = 99 does not compile, and work that changes per customer goes into a local variable or a normal object.
Methods and a lookup by code
A lookup method is a static method in an enum, such as fromCode(String code), that loops over values() and returns the constant whose field matches, or throws an exception when none does.
Tickets print class codes like 3A and SL, but valueOf("3A") matches only Java names such as AC_3_TIER. A static fromCode() method finds a constant by its own data.
Example 6 · Ticket classes with a code, a fare method and fromCode()
enum TrainClass { SLEEPER("SL", 1.0), AC_3_TIER("3A", 2.5), AC_2_TIER("2A", 3.5);
private final String code; private final double multiplier;
TrainClass(String code, double multiplier) { this.code = code; this.multiplier = multiplier; }
int fare(int sleeperFare) { return (int) (sleeperFare * multiplier); }
static TrainClass fromCode(String code) { for (TrainClass t : values()) { if (t.code.equals(code)) { return t; } } throw new IllegalArgumentException("Unknown class code: " + code); }}
public class LookupDemo { public static void main(String[] args) { String[] printedOnTickets = { "3A", "SL", "2S" }; for (String code : printedOnTickets) { try { TrainClass t = TrainClass.fromCode(code); System.out.println(code + " -> " + t + ", Rs. " + t.fare(420)); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } } }}3A -> AC_3_TIER, Rs. 1050 SL -> SLEEPER, Rs. 420 Error: Unknown class code: 2S
What this code does
fromCodeisstatic, because you call it before you have a constant:TrainClass.fromCode("3A"). Inside the enum,values()needs no prefix.- If no code matches, it throws
IllegalArgumentException, likevalueOf.fare()then uses themultiplierof the constant it is called on.
Methods like fare() work on whichever constant they are called on. Compare String codes with equals(), not ==: a code typed by a user is a different String object from the one in the enum.
Next step
Check your understanding
12 quick questions