Codiqo

Learn Java · lesson 59 of 61 · about 9 minutes

Enums with Fields and Methods

Give each enum value its own data and behaviour, like a tiny class.

What you'll learn

  • Add fields and a constructor to an enum
  • Write methods on an enum
  • Loop over values() to look things up

The seat prices

Each kind of seat has its own price: standard is $8.50, premium $11.00 and a recliner $15.00. The desk adds up what tonight's seats cost, Seats cost $45.50, and then a customer asks what their budget will buy, typed in cents, like 1200. The desk finds the comfiest seat that fits: $12.00 buys a premium seat ($11.00), or $5.00 won't buy a seat: a standard seat is $8.50. The price belongs to the seat kind itself, so it goes in the enum.

Values that carry data

An enum is really a class with a fixed set of objects. Each value can carry its own data:

COIN_1P(1), COIN_2P(2), COIN_5P(5); passes a number to each value's constructor, which stores it in a field. Then methods can use that field, just as in any class.

Planets with data

public class Main {
    enum Planet {
        MERCURY(0.38), EARTH(1.0), MARS(0.38), JUPITER(2.53);

        private final double gravity;

        Planet(double gravity) {
            this.gravity = gravity;
        }

        double weightOf(double kg) {
            return kg * gravity;
        }
    }

    public static void main(String[] args) {
        for (Planet p : Planet.values()) {
            System.out.printf("%s: %.1f%n", p, p.weightOf(50));
        }
    }
}

Output

MERCURY: 19.0
EARTH: 50.0
MARS: 19.0
JUPITER: 126.5

Looking values up

A static method on the enum can search values() for a match, for example finding the coin worth 20p. Returning null, or throwing an exception, handles the case where nothing matches.

Finding a value

public class Main {
    enum Coin {
        P1(1), P2(2), P5(5), P10(10), P20(20), P50(50);

        final int pence;

        Coin(int pence) {
            this.pence = pence;
        }

        static Coin worth(int pence) {
            for (Coin c : values()) {
                if (c.pence == pence) return c;
            }
            return null;
        }
    }

    public static void main(String[] args) {
        System.out.println(Coin.worth(20) + " " + Coin.worth(3));
    }
}

Output

P20 null

The comfiest seat for the money

STANDARD(850), PREMIUM(1100), RECLINER(1500); hands each seat kind its price, and the constructor keeps it in final int cents. Adding up s.cents for every seat booked gives the night's total. bestFor(budget) loops over values(), plainest first, and keeps every kind that fits the budget, so the last one kept is the comfiest; if none fits, it stays null, and the desk says even a standard seat is too much.

Tip

The list of values must come first in the enum, ending with a semicolon, before any fields or methods.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.