Friday, 16 January 2015

Enum in java


Java restrict a variable to have only a few redefined variables
Enum constants are implicitly static and final

Advantages of enum:

  • Main benefit of enum is: we can add new constants without breakng exisiting code
  • Enum is type-safe because we can't assign anything else other than predefined Enum constants to an Enum variable.
  • It has its own namespace
  • It can be used inside the Switch statement
  • We can create reference variable in enum
  • Constants are always written in Capital Letters
  • If enum is written outside the class, it should be declared as public or default

Rules
  • enum cannot be overwritten in a method
  • semicolon is optional for enum

Example

class Coffee1
{
 enum CofeeSize{BIG,HUGE,OVERWHELMING}
  CoffeeSize size;  //creating a reference variable
}
public class CoffeeTest
{
public static void main(String args[])
{
  Coffee1 c=new Coffee1();
 c.size=Coffee1.CoffeeSize.BIG;
 }
}

How to access Enum variables

Object.Reference variable=Classname.enumname.value

Ex: To access value BIG
 c.size=Coffee1.CoffeeSize.BIG;

No comments:

Post a Comment