Enum Types in Java

Master enum types including enum fields, methods, constructors, and best practices for the OCP 21 exam.

Table of Contents

1. Enum Basics

An enum (enumeration) is a special class that represents a group of constants. Enums are type-safe and provide better alternatives to integer constants.

1.1 Simple Enum

Example:
// Simple enum enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } // Using enum Day today = Day.MONDAY;
Day tomorrow = Day.TUESDAY;
// Enum comparison if (today == Day.MONDAY) {
    System.out.println("It's Monday!");
} // Enum in switch switch (today) {
case MONDAY -> System.out.println("Start of week");
case FRIDAY -> System.out.println("End of week");
default -> System.out.println("Mid week");
}

1.2 Enum Features

  • Type-safe constants
  • Implicitly final and cannot be extended
  • All constants are public static final
  • Can have fields, methods, and constructors
  • Can implement interfaces
  • Cannot be instantiated with new

2. Enum Fields

Enums can have fields to store additional data for each constant.

Example:
enum Planet {
    MERCURY(3.303e+23, 2.4397e6), VENUS(4.869e+24, 6.0518e6), EARTH(5.976e+24, 6.37814e6), MARS(6.421e+23, 3.3972e6), JUPITER(1.9e+27, 7.1492e7), SATURN(5.688e+26, 6.0268e7), URANUS(8.686e+25, 2.5559e7), NEPTUNE(1.024e+26, 2.4746e7);
    private final double mass;
    // in kilograms private final double radius;
    // in meters Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
public double getMass() {
    return mass;
}
public double getRadius() {
    return radius;
}
} Planet earth = Planet.EARTH;
System.out.println(earth.getMass());
// 5.976E24 System.out.println(earth.getRadius());
// 6378140.0

3. Enum Methods

Enums can have instance methods and static methods.

3.1 Instance Methods

Example:
enum Status {
    PENDING, APPROVED, REJECTED;
    // Instance method public boolean isFinal() {
        return this == APPROVED || this == REJECTED;
    }
public String getDescription() {
    return switch (this) {
        case PENDING ->"Waiting for review";
        case APPROVED ->"Request approved";
        case REJECTED ->"Request rejected";
    };
}
} Status status = Status.PENDING;
System.out.println(status.isFinal());
// false System.out.println(status.getDescription());
//"Waiting for review"

3.2 Static Methods

Example:
enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
    // Static method public static Day fromString(String dayName) {
        return valueOf(dayName.toUpperCase());
    }
public static boolean isWeekend(Day day) {
    return day == SATURDAY || day == SUNDAY;
}
} Day day = Day.fromString("monday");
// MONDAY boolean weekend = Day.isWeekend(Day.SATURDAY);
// true

4. Enum Constructors

Enum constructors are used to initialize enum constants. They are called automatically when enum constants are created.

4.1 Constructor Syntax

Example:
enum Size {
    SMALL("S", 10), MEDIUM("M", 20), LARGE("L", 30), EXTRA_LARGE("XL", 40);
    private final String abbreviation;
    private final int value;
    // Constructor (must be private or package-private) Size(String abbreviation, int value) {
        this.abbreviation = abbreviation;
        this.value = value;
    }
public String getAbbreviation() {
    return abbreviation;
}
public int getValue() {
    return value;
}
} Size size = Size.MEDIUM;
System.out.println(size.getAbbreviation());
//"M" System.out.println(size.getValue());
// 20
Important: Enum constructors must be private or package-private. They cannot be public or protected.

5. Overriding Enum Methods

Each enum constant can override methods to provide constant-specific behavior.

Example:
enum Operation {
    ADD {
        @Override public int apply(int a, int b) {
            return a + b;
        }
}, SUBTRACT {
@Override public int apply(int a, int b) {
    return a - b;
}
}, MULTIPLY {
@Override public int apply(int a, int b) {
    return a * b;
}
}, DIVIDE {
@Override public int apply(int a, int b) {
    if (b == 0) throw new ArithmeticException("Division by zero");
    return a / b;
}
};
// Abstract method - each constant must implement public abstract int apply(int a, int b);
}
Operation op = Operation.ADD;
int result = op.apply(10, 5);
// 15 op = Operation.MULTIPLY;
result = op.apply(10, 5);
// 50

6. Enums in Switch

Enums work well with switch statements and expressions.

Example:
enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
Day day = Day.MONDAY;
// Switch statement switch (day) {
    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY: System.out.println("Weekday");
    break;
    case SATURDAY, SUNDAY: System.out.println("Weekend");
    break;
} // Switch expression String type = switch (day) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY ->"Weekday";
case SATURDAY, SUNDAY ->"Weekend";
};
// Pattern matching with enums (Java 17+) Object obj = Day.MONDAY;
String result = switch (obj) {
    case Day d when d == Day.MONDAY ->"Start of week";
    case Day d when d == Day.FRIDAY ->"End of week";
    case Day d ->"Mid week";
    default ->"Not a day";
};

7. Enums Implementing Interfaces

Enums can implement interfaces, and each constant can provide its own implementation.

Example:
interface Drawable {
    void draw();
}
enum Shape implements Drawable {
    CIRCLE {
        @Override public void draw() {
            System.out.println("Drawing circle");
        }
}, RECTANGLE {
@Override public void draw() {
    System.out.println("Drawing rectangle");
}
}, TRIANGLE {
@Override public void draw() {
    System.out.println("Drawing triangle");
}
};
}
Shape shape = Shape.CIRCLE;
shape.draw();
//"Drawing circle" // Using as interface type Drawable drawable = Shape.RECTANGLE;
drawable.draw();
//"Drawing rectangle"

8. Enum Best Practices

8.1 Common Patterns

Example:
enum Status {
    PENDING {
        @Override public Status next() {
            return APPROVED;
        }
}, APPROVED {
@Override public Status next() {
    return COMPLETED;
}
}, REJECTED {
@Override public Status next() {
    return this;
    // Terminal state }
}, COMPLETED {
@Override public Status next() {
    return this;
    // Terminal state }
};
public abstract Status next();
}
Status current = Status.PENDING;
current = current.next();
// APPROVED current = current.next();
// COMPLETED

8.2 Enum Utility Methods

Example:
enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
    // Get all values public static Day[] getAllDays() {
        return values();
    } // Find by name (with exception handling) public static Day findByName(String name) {
    try {
        return valueOf(name.toUpperCase());
    }
catch (IllegalArgumentException e) {
    return null;
}
} } // Using built-in methods Day[] allDays = Day.values();
// Array of all constants Day monday = Day.valueOf("MONDAY");
// Get constant by name int ordinal = Day.MONDAY.ordinal();
// 0 (position in enum) String name = Day.MONDAY.name();
//"MONDAY"

9. Exam Key Points

Critical Concepts for OCP 21 Exam:

  • Enum Declaration: enum Name { CONSTANT1, CONSTANT2 }
  • Type Safety: Enums provide type-safe constants
  • Implicitly Final: Enums cannot be extended
  • Constants: All enum constants are public static final
  • Enum Fields: Can have instance fields to store data
  • Enum Constructors: Must be private or package-private
  • Constructor Parameters: Passed when declaring constants
  • Enum Methods: Can have instance and static methods
  • Method Overriding: Each constant can override methods
  • Abstract Methods: Enums can have abstract methods (each constant must implement)
  • values(): Returns array of all enum constants
  • valueOf(): Returns enum constant by name
  • ordinal(): Returns position of constant (0-based)
  • name(): Returns name of constant as String
  • toString(): Returns name by default, can be overridden
  • equals() and ==: Both work for enum comparison
  • Switch with Enum: Can use enum in switch statements
  • Implementing Interfaces: Enums can implement interfaces
  • Cannot Instantiate: Cannot use new with enums
  • Constant-Specific Behavior: Each constant can have different behavior

Post a Comment

0 Comments