Friday 9 October 2015

Important points about Enum in Java

1. Enum is type-safe and has its own name-space.
We cannot assign any value other than specified in Enum Constants to Currency variable coin.


public enum Currency {PENNY, NICKLE, DIME, QUARTER};
Currency coin = Currency.PENNY;
coin = 1; //compilation error


2. Enum is reference type like class or interface and you can define constructor, methods and variables inside java Enum which makes it more powerful than Enum in C and C++.

3. Values of enum constants can specify at the creation time:

public enum Currency{PENNY(“1”),NICKLE(“5”), DIME(“10”),QUARTER(“25”)};

However for to specify the values, we need to define a member variable and a constructor because PENNY (1) is calling a constructor which accepts int value.


public enum Currency {
    PENNY(“1”), NICKLE(“5”), DIME(“10”), QUARTER(“25”);
    private String num;

    private Currency(String num) {
            this.num = num;
    }
};


4. Constructor of enum must be private any other access modifier will result in compilation error.

5. We can define methods in enum. To get the value associated with each coin, define a public getValue() method.


public enum Currency {
      PENNY("1 rs"), NICKLE("5 rs"), DIME("10 rs"), QUARTER("25 rs");

      private String value;
      private Currency(String brand) {
            this.value = brand;
      }
     
      public String getCurrValue() {
            return value;
      }
}


6. Enum constants are implicitly static and final and cannot be changed once created.


// The final field EnumTest.Currency.PENNY cannot be assigned
Currency.PENNY = Currency.NICKLE;


7. Enum can be used as an argument on switch statement and with "case:" like int or char primitive type.


Currency currency = Currency.PENNY;
switch (currency) {
case PENNY:
      System.out.println("coin # "+Currency.PENNY);
      break;
case NICKLE:
      System.out.println("coin # "+Currency.NICKLE);
      break;
case DIME:
      System.out.println("coin # "+Currency.DIME);
      break;
case QUARTER:
      System.out.println("coin # "+Currency.QUARTER);
}


8. Since constants defined inside Enum in Java are final you can safely compare them using "==" equality operator.


Currency num = Currency.PENNY;
if(num == Currency.PENNY){
      System.out.println("ENUM compared using equal method !");
}


By the way comparing objects using == operator is not recommended, Always use equals() method or compareTo() method to compare Objects.

9. Java compiler automatically generates static values() method for every enum which returns array of Enum constants in the same order they have listed in enum.


/** It will print all the value of the ENUM. */
for(Currency c : Currency.values()) {
      System.out.println(" # "+ c);
}


10. We can override methods in enum.
Overriding toString() method inside enum to provide meaningful description for enums constants.

11. Two new collection classes EnumMap and EnumSet are added into collection package to support Java Enum.
These classes are high performance implementation of Map and Set interface.

12. private constructor of Enum is not allowed to create instance of enums by using new keyword. Enums constants can only be created inside Enums itself.

13. Instance of Enum is created when any Enum constants are first called or referenced in code (loading the enum in JVM).

14. Enum can implement the interface and override any method like normal class. It’s also worth noting that Enum in java implicitly implement both Serializable and Comparable interface.


public enum Currency implements Runnable {
      PENNY(“1”), NICKLE(“5”), DIME(“10”), QUARTER(“25”);
      private int num;
      ............

      @Override
      public void run() {
            System.out.println("Enum in Java implement interfaces");

      }
}


15. We can define abstract methods inside enum and can provide different implementation for different instances of enum.



enum Currency {

      PENNY("1") {
            @Override
            public String color() {
                  return "copper";
            }
      },
      NICKLE("5") {
            @Override
            public String color() {
                  return "bronze";
            }
      },
      DIME("10") {
            @Override
            public String color() {
                  return "silver";
            }
      },
      QUARTER("25") {
            @Override
            public String color() {
                  return "gold";
            }
      };


      /**
       * ENUM constructor is always private
       * Cannot make object of ENUM using new keyword because
       * of private constructor.
       */
      private Currency(String currency ) {
            this.currency = currency;
      }

      private String currency;

      @Override
      public String toString() {
            return this.name()+" : "+this.getCurrency();
      }

      /** abstract method in ENUM.
       * Need to implement in all ENUM. */
      public abstract String color();

      public String getCurrency() {
            return currency;
      }
}

public class EnumTest {
      public static void main(String[] args) {
            Currency currency = Currency.PENNY;
            System.out.println(currency+", color: "+currency.color());
      }
}
Output: PENNY : 1, color: copper

2 comments:

  1. Thanks, it's a great post. Very helpful !

    While practicing the mentioned facts, I came across something like creating a constructor within enum other than private (i.e, default) !! It runs fine without reporting any compilation errors.
    Example:
    public enum ENUM1 {
    A(1),B("VALUE");
    ENUM1(int i){

    }
    private ENUM1(String value){

    }
    Cheers!!

    ReplyDelete
    Replies
    1. Think of Enums as a class with a finite number of instances. There can never be any different instances beside the ones you initially declare.

      Thus, you cannot have a public or protected constructor, because that would allow more instances to be created.

      Once Enum constants are initialized, they are fixed and there constructors are self-called only. Making it default seems fine as we aren't invoking constructor by any means once enum is initialized.

      Delete

Related Posts Plugin for WordPress, Blogger...