Java Reference
In-Depth Information
4. Once an
enum
type is created, you can declare reference variables of that type, but
you cannot
instantiate objects using the operator
new
. In fact, an attempt
to
instantiate an object using the operator
new
will result in a compilation error.
(Because
enum
objects cannot be instantiated using the operator
new
, the constructor, if
any, of an enumeration cannot be
public
. In fact, the constructors of an
enum
type are
implicitly
private
.)
The
enum
type
Grades
was defined earlier in this section. Let us redefine this
enum
type
by adding constructors, data members, and methods. Consider the following definition:
public enum
Grades
{
A ("Range 90% to 100%"),
B ("Range 80% to 89.99%"),
C ("Range 70% to 79.99%"),
D ("Range 60% to 69.99%"),
F ("Range 0% to 59.99%");
private final
String range;
private
Grades()
{
range = "";
}
private
Grades(String str)
{
range = str;
}
public
String getRange()
{
return range;
}
}
This
enum
type
Grades
contains the
enum
constants
A
,
B
,
C
,
D
, and
F
. It has a
private
named constant
range
of the type
String
, two constructors, and the method
getRange
.
Note that each
Grades
object has the data member
range
. Let us consider the statement:
A ("Range 90% to 100%")
This statement creates the
Grades
object, using the constructor with parameters, with the
string
"Range 90% to 100%"
, and assigns that object to the reference variable
A
. The
method
getRange
is used to return the string contained in the object.
It is not necessary to specify the modifier
private
in the heading of the constructor.
Each constructor is implicitly
private
. Therefore, the two constructors of the
enum
type
Grades
can be written as:
Search WWH ::
Custom Search