Enums

 

  Enums introduced in Java 5. Enum restrict the variable to have one value from  few pre-defined  values〞in other words, one value from an enumerated list.

 

  In the Java programming language, you define an enum type by using the enum keyword. For example month of the year enum type as

 

enum   MonthOfYear { JANUARY, FEBRUARY, MARCH, APRIL , MAY,JUNE, JULY, AUGUST,SEPTMBER, OCTOBER, NOVEMBER, DECEMBER}

 

Here only way to get  a month of the year  will be with a statement something like this:    ize cs MonthOfYear  mon = MonthOfYear.JANAVARY;

There is no rule that enum constants should be in uppercase.

  Each of the enumerated MonthOfYear  types are actually instances of MonthOfYear. In other words, JANUARY, FEBRUARY, MARCH, APRIL etc are  of type MonthOfYear . So enum is a kind of class and each of enumerated values are instances of enum MonthOf Year.

  Enum really is a special kind of class, we can do more than just list the enumerated constant values. We can add constructors, instance variables, methods, and something really strange known as a constant specific class body .

 

  Enums can be declared as their own separate class, or as a class member, but they must not be declared within a method.

  Enum declared outside the class  can not private or protected: Example code

 

            enum   MonthOfYear { JANUARY, FEBRUARY, MARCH, APRIL , MAY,JUNE, JULY, AUGUST,SEPTMBER, OCTOBER, NOVEMBER, DECEMBER}

                        class Month{

                                    MonthOfYear month1;

                        }

                       

                        public class TestMonth{

                         public static void main(String[] args) {

                                    Month mon= new Month();

                                    mon.month1 = MonthOfYear.MARCH;        // enum outside class

                         }

                        }

            key point to remember is that the enum can be declared with only the public or default    modifier

 

   Example of declaring an enum inside a class:

 

                        class Month{

                        enum   MonthOfYear { JANUARY, FEBRUARY, MARCH, APRIL ,                                                           MAY,JUNE,    JULY, AUGUST,SEPTMBER, OCTOBER, NOVEMBER, DECEMBER};                                                                                                  // <--semicolon is optional here

                                   

                                    MonthOfYear month1;

                                    }

 

                        public class TestMonth{

                         public static void main(String[] args) {

                                    Month mon= new Month();

                                    mon.month1 = Month.MonthOfYear.MARCH;       // enum outside class

                         }

                        }

               The syntax for accessing an enum's members depends on where the enum was declared.

 

 

      enums can not declare inside a method. See the below code

 

 

   public class CoffeeTest1 {

              public static void main(String[] args) {

                enum CoffeeSize { BIG, HUGE, OVERWHELMING }  //WRONG! Cannot

                                                            // declare enums

                                                            // in methods

                Coffee drink = new Coffee();

                drink.size = CoffeeSize.BIG;

              }

            }

  Treat our enum values (BIG, HUGE, and OVERWHELMING), as objects that can each have their own instance variables. Then we can assign  values to each of the enum constants at the time the enums are initialized, by passing a value to the enum constructor. Look at the following code:

 

            enum CoffeeSize {

         BIG(8), HUGE(10), OVERWHELMING(16);

        // the arguments after the enum value are "passed"

       // as values to the constructor

       CoffeeSize(int ounces) {

             this.ounces = ounces;  // assign the value to

                                 // an instance variable

       }

        private int ounces;        // an instance variable each enum

                                // value has

       public int getOunces() {

         return ounces;

       }

       }

 

      class Coffee {

       CoffeeSize size;       // each instance of Coffee has-a

                          // CoffeeSize enum

        public static void main(String[] args) {

         Coffee drink1 = new Coffee();

         drink1.size = CoffeeSize.BIG;

         Coffee drink2 = new Coffee();

         drink2.size = CoffeeSize.OVERWHELMING;

         System.out.println(drink1.size.getOunces()); // prints 8

         System.out.println(drink2.size.getOunces()); // prints 16

   }

}

 

            The key points to remember about enum constructors are

 

We can NEVER invoke an enum constructor directly. The enum constructor is invoked automatically, with the arguments  we define after the constant value


We can define more than one argument to the constructor, and we can overload the enum constructors, just as we can overload a normal class constructor

 

  Enum that looks like an anonymous inner class known as constant specific class body, and we can  use it when we need a particular constant to override a method defined in the enum.

           

            Look at the follwing code and understand declaration rules

 

            enum CoffeeSize {

      BIG(8),

      HUGE(10),

      OVERWHELMING(16) {     // start a code block that defines

                             // the "body" for this constant

         public String getLidCode() {   // override the method

                                        // defined in CoffeeSize

           return "A";

         }

      };     // <-- the semicolon is REQUIRED when you have a body

      CoffeeSize(int ounces) {

         this.ounces = ounces;

      }

       private int ounces;

       public int getOunces() {

           return ounces;

       }

       public String getLidCode() {    // this method is overridden

                                   // by the OVERWHELMING constant

        return "B";   // the default value we want to return for

                      // CoffeeSize constants

       }

       }

 

   

 

 

 




Sandeep Joshi
Mathematics, Technology and Programming are my passion. I am a part of Java Ecosystem and through this blog, I contribute to it. I am here to blog about my interests, views and experiences.
I am on Google+ and Facebook.
I feel proud to be listed as a "National Memory Record Holder" in the Limca Book of Records, 2009 and have attempted for an International Memory record in the Guiness Book of Records. I can remember the value of PI upto 10,000 digits after the decimal (3.1415.....). You can contact me on javagenious.com(At)gmal.com ; I would like to hear from you :)