Java Enum Constructor
In this page:
Enums Can Have Constructors
Like a regular class, an enum can define a constructor, and Java automatically calls that constructor once for every constant listed at the top of the enum, at the moment the enum type is first loaded.
Example: Enums Can Have Constructors
enum Level {
LOW, MEDIUM, HIGH;
Level() {
System.out.println("Constant created: " + this);
}
}
public class Main {
public static void main(String[] args) {
Level l = Level.LOW; // constructor runs for every constant at class load
}
}
Login to try C/C++/Java/PHP code in the editor
Passing Values to Enum Constants
Each enum constant can supply its own arguments to the shared constructor by writing them in parentheses after the constant's name, letting every constant carry a different associated value.
Example: Passing Values to Enum Constants
enum Level {
LOW(1), MEDIUM(2), HIGH(3);
int code;
Level(int code) { this.code = code; }
}
public class Main {
public static void main(String[] args) {
System.out.println(Level.HIGH.code);
}
}
Login to try C/C++/Java/PHP code in the editor
Adding Fields to an Enum
Fields declared inside an enum are typically set by the constructor and marked final, giving every constant its own permanent piece of data, such as a numeric code, a display string, or a measurement.
Example: Adding Fields to an Enum
enum Planet {
EARTH(5.97), MARS(0.64);
final double mass; // set by constructor, permanent per constant
Planet(double mass) { this.mass = mass; }
}
public class Main {
public static void main(String[] args) {
System.out.println(Planet.MARS.mass);
}
}
Login to try C/C++/Java/PHP code in the editor
Adding Methods to an Enum
An enum can also define regular methods, just like any other class, and those methods can read the fields that were set by the constructor to compute or return information specific to each constant.
Example: Adding Methods to an Enum
enum Planet {
EARTH(5.97), MARS(0.64);
final double mass;
Planet(double mass) { this.mass = mass; }
double massInKg() {
return mass * 1e21; // uses the field set by the constructor
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Planet.EARTH.massInKg());
}
}
Login to try C/C++/Java/PHP code in the editor
Enum Constructors are Always Private
An enum's constructor is always implicitly private, even if no access modifier is written, because the language itself guarantees the only instances that can ever exist are the fixed set of constants declared in the enum.
Example: Enum Constructors are Always Private
enum Level {
LOW, HIGH;
Level() { // implicitly private, even without writing it
}
}
public class Main {
public static void main(String[] args) {
// new Level(); // would not compile: constructor is private
System.out.println(Level.LOW);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: