What is Java enum?

enum is a java data type, introduced in J2SE 5.0, is useful when you want a variable to hold only a predetermined set of values. You should use enums any time you need a fixed set of constants, including natural enumerated types such as days of the week. You define an enum variable in two steps:
  • Define the enum type with a set of named values.
  • Define a variable to hold one of those values.
Following is an example:

AllowedCreditCard visa = AllowedCreditCard.VISA;

You can think of enum as an alternative to defining a regular class, or you can think of it as a special kind of class. In other words, it has differences and similarities with the regular Java class. The preceding code defines a class named AllowedCreditCard with the restriction that you can create only three instances (a regular class does not have such a restriction) of this class, corresponding to each value defined in the curly braces. However, just like a normal class, a public enum must be in a file named after the enum name. A value stored in an instance of an enum is retrieved by referring to it just like a variable, as shown in this example:

System.out.println("The allowed credit card value: " + visa)

The above code is just a simple example of enum, which looks very similar to enumerations defined in some other languages. However, in Java, enum is a much more powerful concept. You can define an enum as a full-fledged class that contains its own methods, constructors, and fields, implements interfaces, and so on.

Constructors,Methods, and Variables in an enum

Just like a class, an enum can have constructors, methods, and variables in addition to the constants. For example, code snippet below implements an enum named Quark (lines 17 through 36), which has a constructor (lines 26 through 29) that takes two arguments of types char and double. The possible values for these arguments are declared in terms of constants, such as UP and DOWN (lines 18 through 23), which will be passed when an instance of enum is constructed (line 9). This enum also has two final variables, symbol and charge (lines 24 and 25), and two methods, getSymbol() and getCharge().

1. public class EnumTest {
2. public static void main(String[] args) {
3.     int nargs=args.length;
4.     if(nargs < 1){
5.        System.out.println("There must be an argument in the command: 
                   UP, DOWN, STRANGE, CHARM, TRUTH, or BEAUTY");
6.       System.out.println("Example: java EnumTest BEAUTY");
7.       System.exit(0);
8.    }else {
9.         Quark q = Enum.valueOf(Quark.class, args[0].toUpperCase());
10.        char symbol = q.getSymbol();
11.        double charge = q.getCharge();
12.        System.out.println("The electric charge for quark " + symbol +
                    ": " + charge);
13.        System.out.println("The name of the quark: " + q.name());
14.   }
15.  }
16. }

17. enum Quark {
18.   UP('u', 2.0/3.0),
19.   DOWN('d', -1.0/3.0),
20.   CHARM('c', 2.0/3.0),
21.   STRANGE('s', -1.0/3.0),
22.   TRUTH('t', 2.0/3.0),
23.   BEAUTY('b', -1.0/3.0);

24.   private final char symbol;
25.   private final double charge;
26.   Quark(char symbol, double charge){
27.      this.symbol = symbol;
28.      this.charge = charge;
29.   }
30.   public char getSymbol(){
31.       return symbol;
32.   }
33.   public double getCharge(){
34.       return charge;
35.   }
36. }

First note how the enum constants, variables, enum constructor, and the methods are declared in the enum (lines 17 through 36). The enum constants are declared first and terminated with a semicolon before declaring the variable, enum constructors, and methods. The enum Quark is instantiated and used in the class EnumTest (lines 1 through 16). Note the use of the valueOf(…) method of the Enum class, which returns the enum constant of the specified enum type (first argument) with the specified name (second argument). Another useful method of the Enum class is the name() method (line 13), which returns the name of the enum constant as a string, exactly as it is declared in its enum declaration. Here is an example of how to execute this program:

java EnumTest charm

It generates the following output:

The electric charge for quark c: 0.6666666666666666
The name of the quark: CHARM

Although we are using the terminology of instantiating an enum, note that no new operator is used to create an instance of an enum.

Following is a summary of the important points you should remember about an enum:
  • You use the keyword enum and not class to declare an enum.
  • Just like a class, an enum can have constructors, methods, and fields.
  • When you compile, an enum goes into a .class file just like any other class.
  • You cannot instantiate an enum with the new operator.
  • The enums do not participate in class hierarchy: they cannot extend and they  cannot be extended.
  • You cannot directly call an enum constructor.
  • An enum may have a main() method and therefore can be executed by name from the command line like an application.
  • You can use an enum as a valid argument in a switch statement.

Reference(s): SCJP Exam for J2SE 5

No comments:

Post a Comment