Sunday 30 October 2016

Enumerations in Java


The Enumerated data type gives you an opportunity to invent your own data type and define what values the variable of this data type can take.As an Example, one could invent a data type called MaritalStatus which can have four possible values – Single , Married, Divorced or Widowed.

enum Season { WINTER, SPRING, SUMMER, FALL }  

class EnumExample1
{  
// public enum Season { WINTER, SPRING, SUMMER, FALL }  
  
public static void main(String[] args) 
{  
for (Season s : Season.values())  
System.out.println(s);  
 }}  


Another One Example:

enum Department
{
  Assemblly, Manufacturing,Accounts,Stores
}

class Employee
{
  private String name;
  private int age;
  private float salary;
  private Department dept;
  
  public Employee(String n, int a, float s, Department d)
  {
    name = n;
    age = a;
    salary = s;
    dept = d;
  }
  
  public void DisplayData()
  {
    System.out.println(name+ "   " +age+ "   " +salary + "  " +dept  );
    if(dept == Department.Accounts)
          System.out.println(name +" is an Acountant.");
    else
                System.out.println(name +" is not an Acountant.");
  }
}

public class main
{
  public static void main(String[] args)
  {
    Employee e = new Employee("Sagan",28,15555.75f,Department.Accounts);
    e.DisplayData();
  }
}

No comments:

Post a Comment