bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Java/Java Classes
Java•Java Classes

Java Enum Constructor

Enum Constructor

An enum can also have a constructor just like a class.

The constructor is called automatically when the constants are created. You cannot call it yourself.

Here, each constant in the enum has a value (a string) that is set through the constructor:

Runnable example

enum Level {
  // Enum constants (each has its own description) LOW("Low level"), MEDIUM("Medium level"), HIGH("High level"); // Field (variable) to store the description text private String description; // Constructor (runs once for each constant above) private Level(String description) { this.description = description;
}
// Getter method to read the description public String getDescription() {
return description;
}
}
public class Main {
  public static void main(String[] args) {
    Level myVar = Level.MEDIUM; // Pick one enum constant
    System.out.println(myVar.getDescription()); // Prints "Medium level"
  }
}

Note

The constructor for an enum must be private . If you don't write private , Java adds it automatically.

Loop Through Enum with Constructor

You can also loop through the constants and print their values using the values() method:

Runnable example

for (Level myVar : Level.values()) {
  System.out.println(myVar + ": " + myVar.getDescription());
}

Previous

Java Enums

Next

Java User Input (Scanner)

This chapter

Overview
21

Lessons

51m

Read time

1. Java OOP2. Java Classes and Objects3. Java Class Attributes4. Java Class Methods5. Java Constructors6. Java this7. Java Modifiers8. Java Non-Access Modifiers9. Java Encapsulation10. Java Packages11. Java Inheritance12. Java Polymorphism13. Java super14. Java Inner Classes15. Java Abstraction16. Java Interface17. Java Anonymous Class18. Java Enums19. Java Enum Constructor20. Java User Input (Scanner)21. Java Date and Time

On this page

Enum ConstructorLoop Through Enum with Constructor