Enums in Java – Enum Basics, Enum with Fields and Methods

Illustration for Enums in Java – Enum Basics, Enum with Fields and Methods
By Last updated:

Introduction

Enums in Java are special classes that represent a fixed set of constants. They make code more readable, type-safe, and maintainable compared to traditional constant variables.

Why It Matters

  • Ensures type safety over int or String constants.
  • Prevents invalid values at compile-time.
  • Makes code self-documenting and easier to maintain.

When to Use

  • When you have a fixed set of related constants (e.g., days of the week, states).
  • When you want to attach fields/methods to constant values.
  • When implementing state machines or configuration-based logic.

Core Concepts

Basic Enum

public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

Usage:

Day today = Day.MONDAY;
if (today == Day.MONDAY) {
    System.out.println("Start of the week!");
}

Enum with Fields and Methods

public enum Plan {
    BASIC(5), PREMIUM(10), ENTERPRISE(20);

    private int maxUsers;

    Plan(int maxUsers) {
        this.maxUsers = maxUsers;
    }

    public int getMaxUsers() {
        return maxUsers;
    }
}

Usage:

Plan p = Plan.PREMIUM;
System.out.println(p.getMaxUsers()); // 10

Real-World Analogy

Enums are like a menu card in a restaurant. The chef can only cook items listed on the menu (constants). You can also attach prices (fields) and preparation time (methods).


Real-World Use Cases

  • State Machines: Workflow states like PENDING, APPROVED, REJECTED.
  • Configuration: Plans, levels, user roles.
  • Switch Statements: Cleaner branching logic.
switch (today) {
    case MONDAY -> System.out.println("Work hard!");
    case SATURDAY, SUNDAY -> System.out.println("Weekend!");
}

Common Mistakes & Anti-Patterns

  1. Using == with Strings instead of enums:

    • Use enums to avoid typos and invalid values.
  2. Adding mutable fields in enums:

    • Enums should be immutable to maintain thread safety.
  3. Overloading enums with too much logic:

    • Keep behavior focused; use classes for complex logic.

Performance & Memory Implications

  • Enums are singleton instances internally.
  • Memory footprint is minimal since constants are created once.
  • Better performance than using String constants in comparisons.

Comparison Table

Feature Enum Static Constants
Type Safety Yes No
Readability High Medium
Attach Fields/Methods Yes No
Performance Better Good

Best Practices

  • Use enums for fixed sets of related constants.
  • Keep enums immutable.
  • Use EnumSet and EnumMap for collections.
  • Don’t use enums when values change frequently.

Java Version Relevance

Version Change
Java 5 Introduced enums
Java 7+ Switch with strings and enums
Java 8+ Lambdas and streams work seamlessly with enums

Code Example: Enum with Methods

public enum Operation {
    ADD {
        @Override
        public int apply(int a, int b) { return a + b; }
    },
    MULTIPLY {
        @Override
        public int apply(int a, int b) { return a * b; }
    };

    public abstract int apply(int a, int b);
}

class Test {
    public static void main(String[] args) {
        int result = Operation.ADD.apply(2, 3);
        System.out.println(result); // 5
    }
}

Conclusion & Key Takeaways

  • Enums provide a type-safe way to define fixed constants.
  • They can have fields, methods, and constructors for more complex logic.
  • Use them for states, configurations, and well-defined sets of values.

FAQ

  1. What is an enum in Java?
    A special class representing a fixed set of constants.

  2. Can enums have fields and methods?
    Yes, they can have both.

  3. Are enums thread-safe?
    Yes, because they are immutable singletons.

  4. Can enums extend classes?
    No, they implicitly extend java.lang.Enum.

  5. Can enums implement interfaces?
    Yes, enums can implement interfaces.

  6. Can we create enum instances with new?
    No, enums are created internally by the JVM.

  7. What is EnumSet?
    A high-performance set optimized for enums.

  8. Can enums have constructors?
    Yes, but they are always private.

  9. What’s the difference between enum and static constants?
    Enums are type-safe and can have fields/methods; static constants can’t.

  10. When should I avoid enums?
    When values are dynamic or not fixed at compile time.