Let’s have a look at Enum in Java…

Enums are lists of constants. When we need a predefined list of values,we should always use enums.

We should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.

1) All enums implicitly extend java.lang.Enum.

2) Enum in Java are type-safe: Enum has there own name-space. It means your enum will have a type for example “EmployeeType” in below example and you can not assign any value other than specified in Enum Constants.

3) Enum constants are implicitly static and final and can not be changed once created.

4) You can not create instance of enums by using new operator in Java because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.

Following is demo code

enum EmployeeType{
MANAGER, TESTER, DEVELOPER
}
public class NewClass {
// and we have a method getType()
static void getType(EmployeeType et){
System.out.println(et);
}
public static void main(String[] args) {
getType(EmployeeType.TESTER); // no problem
// in a method you can’t put value other than enum type
//getType(1); // ERROR
}
}
Advertisements

One thought on “Let’s have a look at Enum in Java…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s