Enum in Java

Loading

Enums (Enumerations) in Java are a special data type used to define a collection of constants. Enums make code more readable, maintainable, and type-safe by restricting a variable to have only a predefined set of values. Enums were introduced in Java 5 and are defined using the enum keyword.


1. Key Features of Enums

  • Type Safety: Ensures that only valid constants are assigned.
  • Readability: Improves code readability by using meaningful names for constants.
  • Methods and Fields: Enums can have methods, fields, and constructors.
  • Immutability: Enum constants are implicitly final and static.
  • Comparable and Serializable: Enums implement the Comparable and Serializable interfaces by default.

2. Basic Enum Syntax

An enum is defined using the enum keyword, followed by the name of the enum and a list of constants.

Example: Basic Enum

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

public class EnumExample {
    public static void main(String[] args) {
        Day today = Day.WEDNESDAY;
        System.out.println("Today is: " + today);
    }
}

3. Enum with Methods and Fields

Enums can have fields, constructors, and methods. Each constant can override methods if needed.

Example: Enum with Methods and Fields

enum Day {
    SUNDAY("Weekend"),
    MONDAY("Weekday"),
    TUESDAY("Weekday"),
    WEDNESDAY("Weekday"),
    THURSDAY("Weekday"),
    FRIDAY("Weekday"),
    SATURDAY("Weekend");

    private final String type;

    // Constructor
    Day(String type) {
        this.type = type;
    }

    // Method
    public String getType() {
        return type;
    }
}

public class EnumWithMethodsExample {
    public static void main(String[] args) {
        Day today = Day.SATURDAY;
        System.out.println("Today is: " + today);
        System.out.println("Type: " + today.getType());
    }
}

4. Enum with Abstract Methods

Each constant in an enum can provide its own implementation of an abstract method.

Example: Enum with Abstract Methods

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) {
            return a / b;
        }
    };

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

public class EnumWithAbstractMethodsExample {
    public static void main(String[] args) {
        System.out.println("Addition: " + Operation.ADD.apply(10, 5));
        System.out.println("Subtraction: " + Operation.SUBTRACT.apply(10, 5));
        System.out.println("Multiplication: " + Operation.MULTIPLY.apply(10, 5));
        System.out.println("Division: " + Operation.DIVIDE.apply(10, 5));
    }
}

5. Enum in Switch Statements

Enums can be used in switch statements for better readability and type safety.

Example: Enum in Switch Statement

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

public class EnumSwitchExample {
    public static void main(String[] args) {
        Day today = Day.WEDNESDAY;

        switch (today) {
            case MONDAY:
                System.out.println("Start of the work week.");
                break;
            case WEDNESDAY:
                System.out.println("Midweek.");
                break;
            case FRIDAY:
                System.out.println("End of the work week.");
                break;
            default:
                System.out.println("It's a regular day.");
        }
    }
}

6. Enum with Interfaces

Enums can implement interfaces, allowing them to define behavior.

Example: Enum Implementing an Interface

interface Greeting {
    void greet();
}

enum GreetingType implements Greeting {
    HELLO {
        @Override
        public void greet() {
            System.out.println("Hello!");
        }
    },
    GOODBYE {
        @Override
        public void greet() {
            System.out.println("Goodbye!");
        }
    };
}

public class EnumWithInterfaceExample {
    public static void main(String[] args) {
        GreetingType.HELLO.greet();
        GreetingType.GOODBYE.greet();
    }
}

7. Enum with Static Fields and Methods

Enums can have static fields and methods, which are shared across all constants.

Example: Enum with Static Fields and Methods

enum Direction {
    NORTH, SOUTH, EAST, WEST;

    private static final String DESCRIPTION = "Cardinal Directions";

    public static String getDescription() {
        return DESCRIPTION;
    }
}

public class EnumWithStaticExample {
    public static void main(String[] args) {
        System.out.println("Description: " + Direction.getDescription());
    }
}

8. Enum with Custom Methods

Enums can have custom methods that operate on enum constants.

Example: Enum with Custom Methods

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;
    }

    public double surfaceGravity() {
        return 6.67300E-11 * mass / (radius * radius);
    }
}

public class EnumWithCustomMethodsExample {
    public static void main(String[] args) {
        Planet earth = Planet.EARTH;
        System.out.println("Earth's surface gravity: " + earth.surfaceGravity());
    }
}

9. Best Practices

  • Use enums for fixed sets of constants (e.g., days of the week, directions).
  • Use enums in switch statements for type safety.
  • Add methods and fields to enums to encapsulate behavior and data.
  • Use abstract methods in enums to define behavior for each constant.
  • Implement interfaces in enums to provide additional functionality.

By mastering Enums in Java, you can write cleaner, more maintainable, and type-safe code!

Leave a Reply

Your email address will not be published. Required fields are marked *