Java Reference
In-Depth Information
private constructor, which accepts an int parameter. It stores the value of its
parameter in the instance variable. You can add multiple constructors to an enum type. If
you do not add a constructor, a no-args constructor is added. You cannot add a public or
protected constructor to an enum type. All constructors in an enum type declaration go
through parameter and code transformation by the compiler and their access levels are
changed to private . Many things are added or changed in the constructor of an enum type
by the compiler. As a programmer, you do not need to know the details of the changes made
by the compiler.
It defines a
// Declare a private constructor
private SmartSeverity(int projectedTurnaroundDays){
this.projectedTurnaroundDays = projectedTurnaroundDays;
}
It declares a public method
getProjectedTurnaroundDays() , which returns the value of the
projected turnaround days for an enum constant (or the instance of the enum type).
The enum constant declarations have changed to
LOW(30), MEDIUM(15), HIGH(7), URGENT(1);
This change is not obvious. Now every enum constant name is followed by an integer value in
parentheses, for example, LOW(30) . This syntax is shorthand for calling the constructor with
an int parameter type. When an enum constant is created, the value inside the parentheses
will be passed to the constructor that you have added. By simply using the name of the
enum constant (for example, LOW in the constant declaration), you invoke a default no-args
constructor.
The program in Listing 18-4 tests the SmartSeverity enum type. It prints the names of the constants, their
ordinals, and their projected turnaround days. Note that the logic to compute the projected turnaround days is
encapsulated inside the declaration of the enum type itself. The SmartSeverity enum type combines the code for
the Severity enum type and the getProjectedTurnaroundDays() method in the DefectUtil class. You do not have
to write a switch statement anymore to get the projected turnaround days. Each enum constant knows about its
projected turnaround days.
Listing 18-4. A Test Class to Test the SmartSeverity Enum Type
// SmartSeverityTest.java
package com.jdojo.enums;
public class SmartSeverityTest {
public static void main(String[] args) {
for(SmartSeverity s : SmartSeverity.values()) {
String name = s.name();
int ordinal = s.ordinal();
int days = s.getProjectedTurnaroundDays();
System.out.println("name=" + name +
", ordinal=" + ordinal +
", days=" + days);
}
}
}
 
Search WWH ::




Custom Search