Course contentsShow
← Java
Lesson 594 of 2,87014. EnumerationsFree lesson

Static Fields and Methods in Enums

Add static members to enums that are shared across all constants, useful for utility methods and shared data.

Static Fields and Methods in Enums

What You'll Learn

You'll learn how to add static members to enums that are shared across all enum constants, enabling utility methods and centralized data.

The Core Idea

Just like regular classes, enums can have static fields and methods that belong to the enum type itself rather than to any individual constant. These members are shared across all enum constants and can be accessed directly through the enum name.

Think of it like a shared bulletin board in a classroom: while each student (enum constant) has their own desk and belongings (instance fields), the bulletin board (static fields/methods) is accessible to everyone and contains information that applies to the whole class.

Why Use Static Members in Enums?

Static members are perfect for:

  • Utility methods that operate on enum constants
  • Shared counters or configuration data
  • Factory methods that help find or create enum instances
  • Constants that apply to all enum values

Syntax

public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
    
    // Static field - shared by all constants
    private static int instanceCount = 7;
    
    // Static method - utility for the enum type
    public static int getWorkDaysCount() {
        return 5; // Monday through Friday
    }
    
    public static boolean isWeekend(Day day) {
        return day == SATURDAY || day == SUNDAY;
    }
}

Accessing Static Members

// Call static method through the enum name
int workDays = Day.getWorkDaysCount();

// Use static utility methods
boolean weekend = Day.isWeekend(Day.SATURDAY); // true

Key Takeaway: Static fields and methods in enums provide shared functionality and data across all constants, accessed through the enum type name just like static members in regular classes.