How to create enum method


I have this enum : public enum Color { RED, YELLOW; }.
And I want to create a method that returns the opposite color of the actual one. So if I have RED, my method returns YELLOW. But I don’t know the process to follow to do that.
First step : public Color opposite() { return ??? }

>Solution :

If this element is RED, you want to return YELLOW; otherwise you want to return RED. So

public Color opposite() {
    if (this==Color.RED) {
        return Color.YELLOW;
    return Color.RED;

This can be written more concisely as:

public Color opposite() {
    return (this==Color.RED ? Color.YELLOW : Color.RED);

or if you want to allow for more enum values, as:

public Color opposite() {
    switch (this) {
        case RED: return Color.YELLOW;
        case YELLOW: return Color.RED;
        // other possible values
    // required for compiler
    return null;

Leave a Reply Cancel reply