Enums with Fields and Methods

An enum is a fixed set of named constants, and each constant can carry its own data and behaviour.

Java · intermediate · 7 min · 17 steps · free

What you'll learn

EnumsDemo.java

enum Size {
    SMALL(200), MEDIUM(350), LARGE(500);

    final int ml;
    Size(int ml) { this.ml = ml; }

    int price() {
        return switch (this) {
            case SMALL -> 2;
            case MEDIUM -> 3;
            case LARGE -> 4;
        };
    }
}

public class EnumsDemo {
    public static void main(String[] args) {
        Size order = Size.MEDIUM;
        int ml = order.ml;
        int price = order.price();
        Size fromText = Size.valueOf("LARGE");
        int count = Size.values().length;
        System.out.println(order + " " + ml + "ml 
quot; + price + " " + fromText.ordinal() + " " + count); } }

Step by step

  1. Size.MEDIUM is one of exactly three possible Size objects.
  2. Each constant carries data: MEDIUM was created with 350 ml.
  3. Java calls price(). It gets its own variables on the stack.
  4. A switch over this: which constant are we?
  5. Line runs: case MEDIUM -> 3.
  6. price() has finished, so its variables are gone.
  7. The value it returned, 3, is stored in price.
  8. valueOf turns text into the matching constant.
  9. Line runs: enum Size {.
  10. Line runs: enum Size {.
  11. valueOf() has finished, so its variables are gone.
  12. The value it returned, {ml: 500, name: "LARGE", ordinal: 2, hash: 0}, is stored in fromText.
  13. values() returns all constants: 3.
  14. Line runs: enum Size {.
  15. values() returns all constants: 3.
  16. It prints MEDIUM 350ml $3 2 3.
  17. MEDIUM, 350 ml, $3, LARGE's position 2, and 3 sizes in all.

Common mistakes

Best practices

Key takeaways

Check yourself

Can you write new Size(100)?

Answer: No. Enum constructors are private to the enum.

Size.SMALL.ordinal()?

Answer: 0. Positions start at 0.

·

More in More Language Features