Using the Java Enum Type


Instead of using for example static int variables to represent different values in a common category,
Java implements the Enum type which creates a class that contains a list of all its allowed instances.
Other than what is defined within the enum, no other instances are allowed.

An example of Java Enum:


public enum Color {YELLOW, GREEN, ORANGE, ANY}


This defines a separate group of enumerated elements (choices).
The beauty of this is that the Color values cannot be mixed with or confused with another type.
Each enum is treated as if it were a different class. Java Enums can contain functionality too, like in this example:


/**
 *
 * @author www.javadb.com
 */

public enum Fruit {

    APPLE, ORANGE, BANANA, GRAPEFRUIT, KIWI;

    public static Color getColor(Fruit fruit) {

        switch(fruit) {
            case BANANA:
               return Color.YELLOW;
            case ORANGE: case GRAPEFRUIT:
               return Color.ORANGE;
            case KIWI:
               return Color.GREEN;
        }
        return Color.ANY;
    }
}


In this example we implement a getColor method in the Fruit enum.
This method can only be called by passing a Fruit as argument. You cannot pass any other value like an int value for example, only Fruit is valid.
In the switch statment there's no case statement for APPLE since an APPLE can come in many different colors, so if the parameter is an APPLE or any other Fruit that might not be handled in the switch statement, the ANY enum is returned.

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: