Enum methods
- Java course
- Beginner
- Lesson 103/116
- 4 min
Learn to define methods inside enums.
Define methods inside an enum
An enum can contain methods just like a class. These methods use the constant's fields to produce different behavior. This way an enum carries not just values but also behavior.
enum Coffee {
SMALL, LARGE;
public boolean isLarge() {
return this == LARGE;
}
}
System.out.println(Coffee.LARGE.isLarge()); // trueThe method refers to the calling constant with this. The comparison this == LARGE checks constant equality, not reference identity. This is a clean way to bundle conditional behavior in the constant itself.
Per-constant behavior
You can add an abstract method to an enum and override it separately in each constant. This way each constant carries its own behavior and no switch is needed.
enum Operation {
ADD { public int apply(int a, int b) { return a + b; } },
MUL { public int apply(int a, int b) { return a * b; } };
public abstract int apply(int a, int b);
}Each constant acts like an anonymous subclass and writes its own apply body. This keeps behavior next to the constant instead of spreading it out, improving readability. It is a simple form of the strategy pattern.
Practice Write the isLarge method
Define a Coffee enum with SMALL and LARGE constants. Add a public boolean isLarge() method that returns this == LARGE. Print the result of Coffee.LARGE.isLarge().
Starter code
public class Main {
public static void main(String[] args) {
// Define the Coffee enum, add isLarge, print the result
}
}
// Define the Coffee enum hereSample solution
enum Coffee {
SMALL, LARGE;
public boolean isLarge() {
return this == LARGE;
}
}
// inside main:
System.out.println(Coffee.LARGE.isLarge());Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each method call to its result
| Term | Meaning |
|---|---|
Coffee.SMALL.isLarge() |
false |
Coffee.LARGE.isLarge() |
true |
this == LARGE |
Comparison |
isLarge() |
Method |
2 What does the isLarge() method defined inside an enum return?
- Always true
- An array
- Only a String
- true or false depending on the calling constant Correct answer
Explanation: the method checks the calling constant with this; it returns true for LARGE, false otherwise.
3 Call the method
boolean big = Coffee.____.isLarge();
boolean big = Coffee.LARGE.isLarge();
Explanation: Coffee.LARGE.isLarge() returns true.