Working with ENUM
ENUM is just a list of set of value which are static and final.Executing the below code will have a output like one below
public class Test {
public enum Company {
EBAY, PAYPAL, GOOGLE, YAHOO, ATT
}
public static void main(String[] args) {
System.out.println(Company.EBAY);
}
}
Output
EBAY
Now what you can do is to make this constant (static and final) to have further attributes like one below.
public enum Company {
EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25);
private int value;
private Company(int value) {
this.value = value;
}
}
and more Values with overloaded constructor
public class Test1 {
public enum JobStatus {
OPEN("Open", "Its Open", "1"), ERROR("Error", "Its a Error", "2"), WORKING(
"Working", "Its Working", "3"), CLOSED("Closed", "Its Closed");
private String value;
private String label;
private String order;
private JobStatus(String label, String value, String order) {
this.label = label;
this.value = value;
this.order = order;
}
private JobStatus(String label, String value) {
this.label = label;
this.value = value;
}
public String getValue() {
return this.value;
}
public String getLabel() {
return this.label;
}
}
public static void main(String[] args) {
System.out.println(JobStatus.OPEN.value);
System.out.println(JobStatus.OPEN.label);
System.out.println(JobStatus.OPEN.order);
System.out.println(JobStatus.CLOSED.order);
}
}
Output
Its Open Open 1 null
When you need a predefined list of values which do not represent some kind of numeric or textual data, you should use an enum. For instance, in a chess game you could represent the different types of pieces as an enum
enum ChessPiece {
PAWN,
ROOK,
KNIGHT,
BISHOP,
QUEEN,
KING;
}
Assigning Values to ENUM
public enum Company {
EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25);
private int value;
private Company(int value) {
this.value = value;
}
}
- All enums implicitly extend java.lang.Enum.
- MyEnum.values() returns an array of MyEnum’s values.
- Enum constants are implicitly static and final and can not be changed once created.
- Enum can be safely compare using “==” equality operator
- An enum can be declared outside or inside a class, but NOT in a method.
- An enum declared outside a class must NOT be marked static, final , abstract, protected , or private
- Enums can contain constructors, methods, variables, and constant class bodies.
- enum constructors can have arguments, and can be overloaded.