Java Enums

Java Enums

An Enum type field includes the fixed set of constants. The values of enum type fields are in uppercase letters. In java, we are using enum keyword for define an enum type.

Eg: –

public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}

Enum types can represent affixed set of constants. For example the choices on a menu or switch statement, command line flags etc.

Eg: –

public class EnumTest {
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println(“Mondays are bad.”);
break;
case FRIDAY:
System.out.println(“Fridays are better.”);
break;

case SATURDAY: case SUNDAY:
System.out.println(“Weekends are best.”);
break;
default:
System.out.println(“Midweek days are so-so.”);
break;
}
}
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}
}

Enum is a special type of classes and enum type put restriction on the instance values. Enums are implicitly extended java.lang.Enum. So java does not support multiple inheritances. Therefore an enum cannot extend anything else.

Eg: –

public enum myCars{
HONDA,BMW,TOYOTA
};
public class Main {
public static void main(String[] args) {
// TODO code application logic here
myCars currentcar=myCars.BMW;
System.out.println(“My Current Cars : “+ myCars.BMW);
}
}

In java the enum values can pass to the constructor when the constant is created. The constructor for an enum type must be private package or private access. We can’t invoke enum constructor ourselves. It automatically creates the constants when it is defined at the beginning of the enum body.

Eg: –

public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS   (4.869e+24, 6.0518e6),
EARTH   (5.976e+24, 6.37814e6),
MARS    (6.421e+23, 3.3972e6),
JUPITER (1.9e+27,   7.1492e7),
SATURN  (5.688e+26, 6.0268e7),
URANUS  (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);
private final double mass;   // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
private double mass() { return mass; }
private double radius() { return radius; }
// universal gravitational constant  (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
double surfaceGravity() {
return G * mass / (radius * radius);
}
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println(“Usage: java Planet <earth_weight>“);
System.exit(-1);
}
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf(“Your weight on %s is %f%n”,
p, p.surfaceWeight(mass));
}
}

Enum operations

1) Enum embedded inside a class:-

Eg: –

public class Outter {
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE
}
}

In the above example elements are referenced as Outter.Color.RED, Outter.Color.BLUE, etc. Enum that overrides toString method: – In overrides toString method a semicolon is needed after the last element.

2) Enums that override the toString method

Eg: –

public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE;  //; is required here.
 @Override public String toString() {
//only capitalize the first letter
String s = super.toString();
return s.substring(0, 1) + s.substring(1).toLowerCase();
}
}

3)      Enum with additional fields and custom constructor: – Enum constructor supports either private or default package.

Eg: –

public enum Color {
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);
private int code;
private Color(int c) {
code = c;
}
public int getCode() {
return code;
}

4)      Enum that implements interface: – Normally all enum types implements java.io.Serializable, and java.lang.Comparable.

Eg: –

public enum Color implements Runnable {
WHITE, BLACK, RED, YELLOW, BLUE;
public void run() {
System.out.println(“name()=“ + name() +
“, toString()=“ + toString());
}
}

A sample test program to invoke this run() method:

for(Color c : Color.values()) {
c.run();
}

Or,

for(Runnable r : Color.values()) {
r.run();
}

Advantages of enum in java

1)      Enum is type safe: – Enum is type safe. That is we cannot assign anything else other than the predefined enum constant to an enum variable.

2)      Enum has its own name space.

3)      We can use enum in java inside switch statement like int or char primitive type data type.

4)      Adding new constants on enum in java is easy. We can also add new constants without breaking existing code.

Points related to Enum in java:-

1)  Enums in java are type safe: – It has their own name space. We can’t assign any value other than the specified enum values.

Eg: –

public enum Currency {PENNY, NICKLE, DIME, QUARTER};
Currency coin = Currency.PENNY;
coin = 1; //compilation error

2)  Enums in Java are reference type like class or interface:- we can define constructor, methods and variables inside java enum. Java enums are more powerful than c and C++ enums.

3) Specify values of enum constants at the creation time:-

Eg: –

public enum Currency {
PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
private int value;
private Currency(int value) {
this.value = value;
}
};

4)  Enum constants are implicitly static and final and cannot be changed once created.

5)  Enum in java can be used as an argument on switch statement and with “case:” like int or char primitive type

6)  Constants defined inside enum in java are final you can safely compare them using “==“ equality operator.

Eg: –

 Currency usCoin = Currency.DIME;
if(usCoin == Currency.DIME){
System.out.println(“enum in java can be”+
“compared using ==“);
}

7)  Java compiler automatically generates static values() method for every enum in java. Values() method returns array of enum constants in the same order.

Eg: –

public enum Currency {PENNY, NICKLE, DIME, QUARTER};
Currency coin = Currency.PENNY;
 for(Currency coin: Currency.values()){
System.out.println(“coin: “ + coin);
}

8 ) In Java Enum can override methods.

9)  Two new collection classes EnumMap and EnumSet are added into collection package to support java enums. These classes are high performance implementation of Map and Set interface in Java

10)   Cannot create instance of enums by using new operator in java.

11)   Instance of enums in java is created when any enums constants are first called or  referenced in code.

12)   Enum in Java can implement the interface.

13)  We can define abstract methods inside enum in java.

Eg: –

 public enum Currency implements Runnable{
PENNY(1) {
@Override
public String color() {
return “copper”;
}
}, NICKLE(5) {
@Override
public String color() {
return “bronze”;
}
}, DIME(10) {
@Override
public String color() {
return “silver”;
}
}, QUARTER(25) {
@Override
public String color() {
return “silver”;
}
};
private int value;
public abstract String color();
private Currency(int value) {
this.value = value;
}

}