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

Instance Methods in Enums

Define regular instance methods that operate on enum fields, just like in any other class.

Instance Methods in Enums

What You'll Learn

You'll learn how to define regular instance methods in enums that operate on their fields, just like in any other Java class.

The Core Idea

Since enums are classes, they can have regular instance methods that work with their data. These aren't just getters—they can contain any logic that operates on the enum's fields or performs calculations based on the enum constant's state.

Think of it this way: if an enum is like a special club with a fixed number of members (the constants), each member can have their own data (fields) and their own capabilities (methods). These methods can use the fields to perform operations, make decisions, or compute values.

Writing Instance Methods

You define instance methods in enums exactly as you would in a regular class. They have access to the enum's fields and can perform any operations you need:

public enum Planet {
    EARTH(5.97e24, 6.371e6),
    MARS(6.39e23, 3.389e6);
    
    private final double mass;
    private final double radius;
    
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    
    public double getMass() {
        return mass;
    }
    
    public double getRadius() {
        return radius;
    }
    
    // Instance method operating on fields
    public double surfaceGravity() {
        final double G = 6.67430e-11;
        return G * mass / (radius * radius);
    }
    
    // Instance method using other instance methods
    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}

Each enum constant can now call these methods:

double earthGravity = Planet.EARTH.surfaceGravity();
double myWeightOnMars = Planet.MARS.surfaceWeight(70.0);

Key Takeaway: Enums can have regular instance methods that work with their fields, allowing each constant to provide behavior based on its unique data—enums are full-featured classes, not just simple constants.