Course contentsShow
← Java
Lesson 590 of 2,87014. EnumerationsFree lesson

Adding Getter Methods to Enums

Implement accessor methods to retrieve field values from enum constants in a clean, encapsulated way.

Adding Getter Methods to Enums

What you'll learn: How to add accessor methods to enums so you can cleanly retrieve the field values stored in each constant.

Now that you know how to declare fields in enums and initialize them through constructors, you need a way to access those values from outside the enum. Since enum fields are typically private (following encapsulation principles), you add getter methods just like you would in any other class.

Why Getters Matter

Without getter methods, the data you've stored in your enum constants would be locked away and useless. Getters provide controlled, read-only access to enum field values while maintaining encapsulation.

Basic Syntax

public enum Planet {
    MERCURY(3.303e23, 2.4397e6),
    EARTH(5.976e24, 6.37814e6);
    
    private final double mass;   // in kilograms
    private final double radius; // in meters
    
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    
    // Getter methods
    public double getMass() {
        return mass;
    }
    
    public double getRadius() {
        return radius;
    }
}

Using the Getters

Planet earth = Planet.EARTH;
System.out.println(earth.getMass());   // 5.976E24
System.out.println(earth.getRadius()); // 6378140.0

// Useful in loops
for (Planet p : Planet.values()) {
    System.out.println(p + " has mass: " + p.getMass());
}

Think of it this way: each enum constant is like a product on a shelf, and the getter methods are like the labels that let you read the product's details without opening the package.

Key Takeaway: Getter methods in enums work exactly like getters in regular classes—they provide clean, encapsulated access to the data stored in each enum constant's fields.