An enum is a special type of data type which is basically a collection (set) of constants.
public enum Colours{
RED,
GREEN,
BLACK,
YELLOW
}
Here we have a variable Colours of enum type, which is a collection of four constants RED, GREEN, BLACK, YELLOW.
Colour colour = Colour.RED;
public enum Colours{
RED ("R"),
GREEN ("G"),
BLACK ("B"),
YELLOW ("Y");
/* Important Note: Must have semicolon at
* the end when there is a enum field or method
*/
private final String shortCode;
Colours (String code) {
this.shortCode = code;
}
public String getColoursCode() {
return this.shortCode;
}
}
public class EnumDemo
{
public static void main(String[] args) {
Colours colour1 = Colours.RED;
System.out.println(colour1.getColoursCode());
Colours colour1 = Directions.Yellow;
System.out.println(colour2.getColoursCode());
}
}
As you can see in this example we have a field shortCode for each of the constant, along with a method getColoursCode() which is basically a getter method for this field. When we define a constant like this RED ("R"), it calls the enum constructor (Refer the constructor Colours in the above example) with the passed argument. This way the passed value is set as an value for the field of the corresponding enum’s constant [RED(“R”) => Would call constructor Colours(“R”) => this.shortCode = code => this.shortCode = “R” => shortCode field of constant RED is set to “R”].
Important points to Note:
public enum Directions{
EAST,
WEST,
NORTH,
SOUTH
}
public class EnumDemo
{
Directions dir;
public EnumDemo(Directions dir) {
this.dir = dir;
}
public void getMyDirection() {
switch (dir) {
case EAST:
System.out.println("In East Direction");
break;
case WEST:
System.out.println("In West Direction");
break;
case NORTH:
System.out.println("In North Direction");
break;
default:
System.out.println("In South Direction");
break;
}
}
public static void main(String[] args) {
EnumDemo obj1 = new EnumDemo(Directions.EAST);
obj1.getMyDirection();
EnumDemo obj2 = new EnumDemo(Directions.SOUTH);
obj2.getMyDirection();
}
}
class EnumDemo
{
public static void main(String[] args) {
for (Directions dir : Directions.values()) {
System.out.println(dir);
}
}
}