- Enumerations are of class type, and have all the capabilities that a Java class has.
- Enumerations can have Constructors, instance Variables, methods and can even implement Interfaces. Constructors cannot be public
- Enumerations are not instantiated using new keyword.
- All Enumerations by default inherit java.lang.Enum class.
- Enumeration with Constructor, instance variable and Method
- Because they are constants, the names of an enum fields are created in uppercase (like other Java constants).
- You can use an enum any time you need to represent a fixed set of constants.
How to Define and Use an Enumeration
An enumeration can be defined simply by creating a list of enum variable. Let us take an example for list of Subject variable, with different subjects in the list.
enum Subject{
Java, Cpp, C, Dbms
}
Identifiers Java, Cpp, C and Dbms are called enumeration constants. These are public, static final by default.
Variables of Enumeration can be defined directly without any new keyword.
Subject sub
Variables of Enumeration type can have only enumeration constants as value.
sub = Subject.Java;
Example of Enumeration
enum WeekDays {
sun, mon, tues, wed, thurs, fri, sat
}
class Test{
public static void main(String args[]) {
WeekDays wk;
wk = WeekDays.sun;
System.out.println("Today is "+wk);
}
}
Output :
Today is sun
Values( ) and ValueOf( ) method
All the enumerations have values() and valueOf() methods in them. values() method returns an array of enum-type containing all the enumeration constants in it. Its general form is,
public static enum-type[ ] values()
valueOf() method is used to return the enumeration constant whose value is equal to the string passed in as argument while calling this method. It's general form is,
public static enum-type valueOf (String str)
enum Student {
John(11), Bella(10), Sam(13), Viraaj(9);
private int age; //age of students
int getage() { return age; }
Student(int age) { //Constructor cannot be public
this.age= age;
}
}
public class EnumDemo{
public static void main( String args[] ) {
Student S=Student.Bella;
System.out.println("Age of Viraaj is " +Student.Viraaj.getage()+ "years");
System.out.println("Age of "+Student.valueOf("Bella")+" is " +(Student.valueOf("Bella")).getage()+ " years");
System.out.println(S.values());
for(Student s : S.values()){
System.out.println(s);
}
}
}
Output
Age of Viraaj is 9years
Age of Bella is 10 years
[LStudent;@7e199049
John
Bella
Sam
Viraaj
A Java enum switch statement example
You can also use a Java enum in a switch statement. Here’s the source code for a complete Java enum switch statement example:
public class JavaEnumSwitchCaseExample {
enum Margin {
TOP, RIGHT, BOTTOM, LEFT
}
public static void main(String[] args) {
System.out.println(getMarginValue(Margin.TOP));
}
/**
* @param A valid Margin value.
* @return A String representing the value for the given Margin,
* or null if the Margin is not valid.
*/
public static String getMarginValue(Margin margin) {
// use the enum values in our switch statement here
switch (margin) {
case TOP: return "1em";
case RIGHT: return "12px";
case BOTTOM: return "1.5em";
case LEFT: return "6px";
default: return null;
}
}
}
You can also use a Java enum in a switch statement. Here’s the source code for a complete Java enum switch statement example:
public class JavaEnumSwitchCaseExample {
enum Margin {
TOP, RIGHT, BOTTOM, LEFT
}
public static void main(String[] args) {
System.out.println(getMarginValue(Margin.TOP));
}
/**
* @param A valid Margin value.
* @return A String representing the value for the given Margin,
* or null if the Margin is not valid.
*/
public static String getMarginValue(Margin margin) {
// use the enum values in our switch statement here
switch (margin) {
case TOP: return "1em";
case RIGHT: return "12px";
case BOTTOM: return "1.5em";
case LEFT: return "6px";
default: return null;
}
}
}
enums and implementation of serialization and singleton:
1) Singleton using Enum in Java
This is the way we generally declare Enum Singleton , it may contain instace variable and instance method but for sake of simplicity I haven’t used any, just beware that if you are using any instance method than you need to ensure thread-safety of that method if at all it affect the state of object. By default creation of Enum instance is thread safe but any other method on Enum is programmers responsibility.
/**
You can acess it by EasySingleton.INSTANCE, much easier than calling getInstance() method on Singleton.
2) Enum Singletons handled Serialization by themselves
Another problem with conventional Singletons are that once you implement serializable interface they are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singleton as shown in below example :
//readResolve to prevent another instance of Singleton
This can become even more complex if your Singleton Class maintain state, as you need to make them transient, but within Enum Singleton, Serialization is guaranteed by JVM.
3) Creation of Enum instance is thread-safe
As stated in point 1 since creatino of Enum instance is thread-safe by default you don't need to worry about double checked locking.
1) Singleton using Enum in Java
This is the way we generally declare Enum Singleton , it may contain instace variable and instance method but for sake of simplicity I haven’t used any, just beware that if you are using any instance method than you need to ensure thread-safety of that method if at all it affect the state of object. By default creation of Enum instance is thread safe but any other method on Enum is programmers responsibility.
/**
* Singleton pattern example using Java Enumj
*/
public enum EasySingleton{
INSTANCE;
}
You can acess it by EasySingleton.INSTANCE, much easier than calling getInstance() method on Singleton.
2) Enum Singletons handled Serialization by themselves
Another problem with conventional Singletons are that once you implement serializable interface they are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singleton as shown in below example :
//readResolve to prevent another instance of Singleton
private Object readResolve(){
return INSTANCE;
}
This can become even more complex if your Singleton Class maintain state, as you need to make them transient, but within Enum Singleton, Serialization is guaranteed by JVM.
3) Creation of Enum instance is thread-safe
As stated in point 1 since creatino of Enum instance is thread-safe by default you don't need to worry about double checked locking.
No comments:
Post a Comment