Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Java Enum Constructors Explained with Practical Example

Java Enum Constructors Explained

Learn how to define and use constructors within Java enums through a clear, step‑by‑step example.

Before exploring enum constructors, review the basics of Java enum types.

In Java, an enum class can contain a constructor just like any other class. The constructor is typically private—accessible only inside the enum itself—or package‑private, which limits access to the same package.


Example: Enum Constructor in Action

enum Size {
   SMALL("The size is small."),
   MEDIUM("The size is medium."),
   LARGE("The size is large."),
   EXTRALARGE("The size is extra large.");

   private final String pizzaSize;

   private Size(String pizzaSize) {
      this.pizzaSize = pizzaSize;
   }

   public String getSize() {
      return pizzaSize;
   }
}

class Main {
   public static void main(String[] args) {
      Size size = Size.SMALL;
      System.out.println(size.getSize());
   }
}

Output

The size is small.

In this illustration, the Size enum defines a private constructor that accepts a String argument. The enum constants—SMALL, MEDIUM, LARGE, and EXTRALARGE—invoke this constructor, passing a descriptive message. The pizzaSize field stores the value, and the public getSize() method exposes it.

Because the constructor is private, it cannot be called from outside the enum. Instead, each constant automatically triggers the constructor during class initialization. In the Main class, selecting Size.SMALL creates an instance whose getSize() method returns the assigned string.

Java

  1. Master Java Operators: Types, Syntax, & Practical Examples
  2. Master Java Constructors: Types, Usage, and Practical Examples
  3. Mastering Java's super Keyword: Advanced Usage & Practical Examples
  4. Mastering Java Interfaces: Concepts, Implementation, and Best Practices
  5. Master Java Enums: A Complete Guide to Enums & Enum Classes
  6. Mastering String Representations in Java Enums
  7. Mastering Java EnumMap: Efficient Key-Value Mapping with Enums
  8. Java EnumSet: Creation, Operations, and Performance Tips
  9. Constructor Overloading in Java – Explained with Practical Code Examples
  10. Understanding Java Constructors: Initialization and Best Practices