Saturday, September 19, 2015

[Java] Enums

1. Example
// Think of it as constant value
Currency usCoin = Currency.DIME;
if (  usCoin == Currency.DIME )


public class CurrencyDenom
{
         public static final int PENNNY = 1;
         public static final int NICKLE = 5;
         public stati final int DIME  =10;
         public static final int QUARTER = 25;
}
public class Currency
{
         private int currency;// CurrencyDenom.PENNY, CurrencyDenom.NICKLE 
                                         // CurrencyDenom.DIME, CurrencyDenom.QUARTER
}


Limitations:
1) No type-safety
currency can be assigned any value
2)No meaningful printing
print "NICKLE" print "5" instead of "NICKLE"
3)No namespace
need to access by class name like CurrencyDenom.PENNY instead of PENNY

2. Implementation

public enum Currency
{
     PENNY, NICKLE, DIME, QUARTER
};

Java Enum is type like class and interface and can be used to define a set of constants.



1) Type-safety
Currency coin = Currency.PENNY;
coin =1; // compilation error

2) Reference type
can define CONSTRUCTOR, method and variables

3) Specify values of enum constants at the creation time
public enum Currency{PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};
NOTE: for this to work you need a member variable and a constructor because PENNY(1) is actually calling a CONSTRUCTOR which accepts int value, see below example

public enum Currency 
{
      PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
      private int value;
      private Currency(int value) { this.value = value;}

}
Constructor of enum in java must be private (LIKE a singleton )any other access modifier will result in compilation error.
Now to get the value associated with each coin you can define a public getValue() method inside java enum like any normal java class. Also semi colon in the first line is optional.

4) Enum constants are implicitly static and final and can not be changed once created.
Currency.PENNY = Currency.DIME;
The final field EnumExamples.Currency.PENNY cannot be assigned.

5) Use in switch like char or int
Currency usCoin = Currency.DIME;
switch(usCoin)
{
        case PENNY:
           break;
        case NICKLE:
           break;
        case DIME:
          break;
        case QUARTER:
//NOTE:  no need to break in the last case, it won;t be overwritten
}

6) Equality operator
Currency usCoin =  Currency.DIME;
if (  usCoin == Currency.DIME )
{
     System.out.println("enum in java can be compared using ==");
}


NOTE: comparing objects using == operator is not recommended, Always use equals() method or compareTo() mehtod to compare Objects.

7) automatically generate "static" values() [static use class to call], which return array of Enum constants in the same order.
for ( Currency coin:Currency.values() )
         System.out.println("coin: " + coin);

coin:PENNY
coin:NICKLE
coin:DIME
coin:QUARTER

8)Meaningful printing, override toString()
public enum Currency {

........
@Override
public String toString()
{
       switch (this)
       {
                case PENNY:
                     break;
                case NICKLE:
                     break;
                case DIME:
                     System.out.println("Dime: "+ value);
                     break;
                case QUARTER:
       }

       return super.toString();
}

};
Currency usCoin = Currency.DIME;
System.out.printon(usCoin);

Output:
Dime:10



9) EnumMap and EnumSet
10) You can not create instance of enums by using new operator because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.
11) Instance of Enum in Java is created when any of Enum constants are first called or referenced in code.
12)  Implement the interface 
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 value;
     ........
     @Override
      public void run ()
      {
              System.out.println("Enum in java implement interfaces");
      }

     
}


13) Define abstract method
public enum Currency implements Runnable
{
       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 "silver";          
                    }
       }

       private int vlaue;
       public abstract String color();
       private Currency (int vlaue)
       {
                  this.vlaue = vlaue;
       }

}

In this example since every coin will have different color we made the color() method abstract and let each instance of Enum to define there own color. You can get color of any coin by just calling color() method as shown in below example of java enum:
System.out.println("Color: " + Currency.DIME.color());


14) Enum valueOf(String) :convert a String into enum
num valueOf() is a static method which takes a string argument and can be used to convert a String into enum. 
One think though you would like to keep in mind is that valueOf(String) method of enum will throw "Exception in thread "main" java.lang.IllegalArgumentException: No enum const class" if you supply any string other than enum values.


enum Mobile {
   Samsung(400), Nokia(250),Motorola(325);
  
   int price;
   Mobile(int p) {
      price = p;
   }
   int showPrice() {
      return price;
   } 
}
Mobile ret;
     ret = Mobile.valueOf("Samsung"); 
     System.out.println("Selected : " + ret);   
Selected : Samsung
http://www.tutorialspoint.com/java/lang/enum_valueof.htm 
15) ordinal() and name(Enum):
converting Enum to String 
ordinal() method of Java Enum returns position of a Enum constant as they declared in enum.
name() of Enum returns the exact string which is used to create that particular Enum constant.
name() method can also be used for converting Enum to String in Java.

  Mobile ret = Mobile.Motorola;
     System.out.println("MobileName = " + ret.name()); 
MobileName = Motorola
http://www.tutorialspoint.com/java/lang/enum_name.htm 
3. similar ones



No comments:

Post a Comment