Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading