Wednesday 20 August 2014

Enum in Java



Enum concept introduced in JDK 1.5 version.

Java enum more powerful than other language.

The main purpose of enum is if we want to developed or represent group of constant then we should go for enum.


e.g

      enum Friend
{
       kunal,sachin,jagdish,atish,vaibhav,vishal;
        
}



Internally enum represent as liked this Class concepts


  Every enum by default public static final
  Every constant represent as object of type enum

 
class Friend
{
Public static final Friend sachin=new Friend();
Public static final Friend atish=new Friend();
.
.
.
}


Specialty of java enum:


In old language we represent only constant but in java enum we declare variable,constructor and method also and enum can have main method also we run enum from cmd also

i.e java enum is more powerful than other languages;
//simple.java

enum month                                                                            
{
                jan,feb,march,may;

public static void main(String[] args)
                {
                                System.out.println("Hello World!");
                  month n=month.jan;
       System.out.println(n);
                 
                }
}
o/p:

 

 

Some valid combination java enum:


  • ·         It can be inside the class.
  • ·         class can be inside  enum.
  •      But inside method does not allowed

     
enum is direct child class of java.lang.Enum so we cannot extend any other enum

so that it cannot extend any another enum.

it can implement any number of interface.


One of the most important interview question I faced


                                                                              

Difference between enum Enum and Enumeration..??


enum:-it is used for creating java enum it is keyword

Enum:it is class represent in java.lang.Enum which act as based class for all java enum

Enumaration-it is cursor it used for retrieving element from collection one by one.
 

// EnumDemoExample.java
enum Friend
{
       kunal,sachin,jagdish,atish,vaibhav,vishal;
     int x=10;
       Friend()
  {
         System.out.println("inside the constructor");
  }

}
public class EnumDemoExample {

       public static void main(String[] args) {
              // TODO Auto-generated method stub

             
             
              Friend f=Friend.kunal;
        System.out.println("hellow friend");
        System.out.println(f.x);
       Friend f1[]=Friend.values();
       for(Friend a:f1)
       {
              System.out.println(a+"---"+a.ordinal());
       }
       }

}

O/P-
inside the constructor
inside the constructor
inside the constructor
inside the constructor
inside the constructor
inside the constructor
hellow friend
10
kunal---0
sachin---1
jagdish---2
atish---3
vaibhav---4
vishal---5

 



No comments:

Post a Comment