Java › Enums
How do you add fields, constructors, and methods to a Java enum, and how would you implement an enum representing planets with mass and radius that calculates surface gravity?
IntermediateAnswer
Since each enum constant is a singleton instance, an enum can have instance fields (typically final, set via a private constructor invoked implicitly for each constant), and both regular instance methods (shared logic across all constants) and constant-specific method bodies (where an individual constant overrides a method uniquely for itself) -- letting an enum encapsulate not just a name but genuine associated data and behavior, going well beyond what a simple set of constants could express.
public enum Planet {
MERCURY(3.303e+23, 2.4397e6),
EARTH(5.976e+24, 6.37814e6);
private final double mass; // kg
private final double radius; // meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double surfaceGravity() {
final double G = 6.67300E-11;
return G * mass / (radius * radius);
}
}
System.out.println(Planet.EARTH.surfaceGravity());Real-world example A physics simulation models each solar system planet as an enum constant carrying its own mass and radius, with a shared surfaceGravity() calculation method available uniformly across every planet constant, encapsulating both the astronomical data and the derived calculation logic in one type-safe, self-documenting structure.