Enum Members
layout: default
title: enum Member
Since an enum is really a class, you are allowed to provide your own methods and fields in the enum declaration.
Fields and Methods¶
We can give the enum fields and methods, including constructors.
- These come after the constant declarations.
This version of Day has a field for the name, and a toString() to print out that value.
public enum Day2 {
// ...
final private String name;
@Override
public String toString() {
return name;
}
public String getName() {
return name;
}
}
Practice Exercise¶
enumfields are not implicitlyfinal.
enum Constructors¶
We can initialize the field for each constant by providing a constructor.
Call the constructor when declaring the constant. * However, the constructor is still declared after the constants.
public enum Day2 {
// Constants must be first
SUNDAY("Sunday"), // calling constructor
MONDAY("Monday"),
TUESDAY("Tuesday"),
WEDNESDAY("Wednesday"),
THURSDAY("Thursday"),
FRIDAY("Friday"),
SATURDAY("Saturday");
Day2(String d){
name = d;
}
final private String name;
@Override
public String toString() {
return name;
}
public String getName() {
return name;
}
}
public or protected.
Practice Exercise¶
In an
enumdeclaration, a constructor declaration with no access modifiers isprivate.1
Drill¶
EnumeratedTypes/com.example.enums.drills.cards
- Create a
publicenumcalledSuitwith the constants (in order)HEARTS, SPADES, CLUBS, DIAMONDS.- Add a
private namefield toSuit.- Add a one-arg constructor to
Suitand set thenamefields toHearts,Spades,Clubs,Diamonds.- Override the
toStringmethod to output thisname.- Create a
publicenumcalledRankwith the constants (in order)TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE.- Add a
private valuefield toRank.- Add a one-arg constructor to
Rankand set thevaluefield to2-10for numbers,10forJACK,QUEEN, andKING, and11forACE.- Add a
getValue()method to return thevalue.- Uncomment the code in
CardTestto test your enums.
[1] https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.2