Monday, July 4, 2016

Java : Usage of Enums with Example

Enums are the set of some constants in java. In other words, if you want to define some constants in your program which you are going to use throughout and need not be changed, use Enums. For example, in an application you can represent the different statuses as a list of constants and take Enums type.

Example:
public enum Status{
APPROVED,DECLINED,IN-PROGRESS,PENDING,NEW
}

Hence, it is recommended to use the Enums every-time when a variable seems to take the value definitely from the set of defined values.

Full Java Example to Demonstrate it:

public class EnumExample {

public enum Status {
APPROVED,DECLINED,IN-PROGRESS,PENDING,NEW
}

Status statusVal;

public EnumExample(Status statusVal) {
this.statusVal = statusVal;
}

public void statusDetails() {
switch (statusVal) {
case APPROVED:
System.out.println("Application has been approved");
break;

case DECLINED:
System.out.println("Application has been declined");
break;

case PENDING:
System.out.println("Application is in pending status");
break;

default:
System.out.println("Application is in New status");
break;
}
}

public static void main(String[] args) {
EnumExample approved = new EnumExample(Status.APPROVED);
approved.statusDetails();
EnumExample declined = new EnumExample(Status.DECLINED);
declined.statusDetails();
EnumExample pending = new EnumExample(Status.PENDING);
pending.statusDetails();

}
}
Output would be like: 
Application has been approved
Application has been declined
Application is in pending status



Some points to note about Enums:

* Enums are truely type safe. Means once the value is assigned to an enum  can not be overridden.
* Enum constants are implicitly static and final .
* Enum constants can only be created inside Enums itself. These can not be created using new operator. That's the reason Enums are preferred over the Singleton class.
* Enums can not be declared in a method.
* Enum constructors can have arguments.
* Enum constructors can be overloaded.

No comments:

Post a Comment