Java
Enum methods
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()); // true
The 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.
Exercise 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().
Show example solution
enum Coffee {
SMALL, LARGE;
public boolean isLarge() {
return this == LARGE;
}
}
// inside main:
System.out.println(Coffee.LARGE.isLarge());
Test yourself
-
Match each method call to its result
- Coffee.SMALL.isLarge()
- false
- Coffee.LARGE.isLarge()
- true
- this == LARGE
- Comparison
- isLarge()
- Method
-
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
Show answer
true or false depending on the calling constant — the method checks the calling constant with this; it returns true for LARGE, false otherwise.
-
Call the method
boolean big = Coffee.____.isLarge();
Show answer
boolean big = Coffee.LARGE.isLarge();
Next lesson: switch with enum