Enums with Fields and Methods
Add fields, constructors, and methods to enums to encapsulate behavior.
Enums with Fields and Methods
Enum constants can carry data. You add fields by declaring them and a constructor. The constructor is automatically private.
Declaring Fields in Enums
Each enum constant calls the constructor when the class loads. Field values are set once and are immutable (when declared final).
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);
private final double mass; // kilograms
private final double radius; // meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass() { return mass; }
public double radius() { return radius; }
}All lessons in this course
- Defining and Using Enums
- Enums with Fields and Methods
- Switch Expressions with Enums
- EnumSet and EnumMap