# Enum example

This is from page 151 of Java in a Nutshell :

public enum RegularPolygon{
//The ; is mandatory for enums that have parameters
TRIANGLE(3), SQUARE(4), PENTAGON(5), HEXAGON(6);

private Shape shape;

public Shape getShape(){
return shape;
}

private RegularPolygon(int sides){

switch(sides){

case 3:
//We assume that we have some general constructors
// for shapes that take the side length and
//angles in degrees as parameters
shape = new Triangle(1,1,1,60,60,60);
break;
case 4:
shape = new Rectangle(1,1);
break;
case 5:
shape = new Pentagon(1,1,1,1,1,108,108,108,108,108);
break;
case 6:
shape = new Hexagon(1,1,1,1,1,1,120,120,120,120,120,120);
break;

}
}
}

Not knowing that much about enums, I am wondering a) what the upper and lowercase forms for the polygons are, b) where the Shape class comes from, and c), where the Rectangle class interfaces with RegularPolygon.SQUARE . . .? I expect it's my lack of knowledge on the topic that is wanting, but my head is getting sore from the wall-banging.
LVL 17
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Senior Java ArchitectCommented:
I'm betting that Shape, Triangle, Rectangle, Pentagon, and Hexagon are all classes that are defined elsewhere. The all-caps TRIANGLE, SQUARE, PENTAGON, and HEXAGON values are the four possible values in the RegularPolygon enum. Maybe check earlier in the book to see if a previous example defines those classes?
0

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Author Commented:
>>are all classes that are defined elsewhere.<< Could be. I thought I was getting examples that concerned enums though, and fail to see how illustrating a concept (enum in this case) by showing that it can reference regular classes but using the same names as the enumerated type can be clear . . . unless I have understood absolutely nothing, which is possible natch.

There are no earlier references to the lowercase classes in the book , , , afaics. But even if there are, it makes using this book as a reference pretty questionable. I already found a bunch of highly dubious statements about what's going on in the Java language elsewhere in the book, making me unsure whether to trust in my own misunderstandings or 'what'.
0
Senior Java ArchitectCommented:
This does indeed seem to be a poor example of enums. I would write the constructor as taking the appropriate Shape object, not the number of sides, which would let me avoid that switch statement:

public enum RegularPolygon {
TRIANGLE(new Triangle(1, 1, 1, 60, 60, 60)), // A class called Triangle is assumed to have a constructor that takes three side lengths and three angles.
SQUARE(new Rectangle(1, 1)), // A class called Rectangle is assumed to have a constructor that takes the short side length and the long side length, both of which are equal in squares.
PENTAGON(new Pentagon(1, 1, 1, 1, 1, 108, 108, 108, 108, 108)),
HEXAGON(new Hexagon(1, 1, 1, 1, 1, 1, 120, 120, 120, 120, 120, 120));

private Shape shape;

private RegularPolygon(Shape shape) {
this.shape = shape;
}

public Shape getShape() {
return shape;
}
}

Essentially, this enum is storing special cases of the various Shape classes; that is, it's holding references to instances of those shapes where all the sides have equal lengths and all the angles are equal.
0
Author Commented:
Yes, thanks CP.

I came across this simple explanation :
Quote:
A simple usage will look like this:

public enum DIRECTION {
EAST,
WEST,
NORTH,
SOUTH        //optionally can end with ";"
}
Here EAST, WEST, NORTH and SOUTH are final static inner classes of Direction of type Direction extends java.lang.Enum.
Unquote.

I think that now makes a bit more sense along with what you commented. But why enums are so praiseworthy if all they are are static inner classes in another guise, I am not sure. )
0
Senior Java ArchitectCommented:
You can do a switch statement on an enum value and Eclipse will warn you if you don't have a case statement for each possible value, which comes in handy a lot. In many places, it's nice knowing that when you have a variable of an enum type, you can be 100% sure its value will be one of the values declared in the enum.

For example, you could have some code like this:
public static final int WORK_QUEUE_MAIN = 1;
public static final int WORK_QUEUE_ALTERNATE = 2;

public static final int WORK_SCHEDULE_IMMEDIATE = 1;
public static final int WORK_SCHEDULE_HOURLY = 2;

public void doSomeWork(int workQueue, int workSchedule)
{
...
}

public void someOtherMethod()
{
doSomeWork(WORK_QUEUE_MAIN, WORK_SCHEDULE_HOURLY);
}
Since that method takes two integers, a developer could accidentally pass the parameters in the wrong order and the error would only become obvious at runtime:
public void someOtherMethod()
{
doSomeWork(WORK_SCHEDULE_HOURLY, WORK_QUEUE_MAIN);
}
Or a developer could pass values the method isn't written to handle:
public void someOtherMethod()
{
doSomeWork(0, 3);
}
With enums, you could write the code like this, instead:
public enum WorkQueue
{
MAIN,
ALTERNATE
}

public enum WorkSchedule
{
IMMEDIATE,
HOURLY
}

public void doSomeWork(@NonNull WorkQueue workQueue, @NonNull WorkSchedule workSchedule)
{
...
}

public void someOtherMethod()
{
doSomeWork(WorkQueue.MAIN, WorkSchedule.ALTERNATE);
}
This way, the values are checked when the code is compiled and the developer can't get the parameters wrong (as easily).
0
Commented:
Like CPColin pointed out there's lots of advantages for enums over final static int constants.

Another one that we've started to adopt more and more is encoding extra information within the enum - which goes back to the original class you started with.

So we have enums like this:

public enum ValuesAppVersion {
kDev(0, "dev"),
kQaTest(1, "qatest"),
kPlayTest(2, "playtest"),
kLive(3, "live");

private final int dbValue;
private final String version;

private ValuesAppVersion(int dbValue, String version) {
this.dbValue = dbValue;
this.version = version;
}

public int getDBValue() {
return dbValue;
}

public String getVersion() {
return version;
}
}

which you allows you to do things like:

public void setAppVersion(ValuesAppVersion appVersion) {
String name = appVersion.getVersion() ;
int id = appVersion.getDBValue() ;
...
}

which is awkward at best to do with simple constants or other things you want to "keep joined together".

Doug
0
Author Commented:
So then, Doug,

public void setAppVersion(ValuesAppVersion appVersion) {

. . .  you are presumably saying there that "appVersion" must be  / is, one of :

kDev,   kQaTest,   kPlayTest,   kLive    ?

Trying, like a dunce, to get my head into the reason for calling setAppVersion at all, when one already knows the enum member (as you are effectively calling it by using : ValuesAppVersion.kLive).  Or . . .  not? ;)
0
Senior Java ArchitectCommented:
I think the idea is that the setAppVersion() method is somewhere else, not in the enum.
0
Commented:
Right - like CPColin said, the setAppVersion() is somewhere else and needs to know what version of the app we're using.

Passing an enum makes that clear and type safe and with methods added to the enum you can group all of the properties of that "constant" together.

Say for instance we wanted to take real credit cards on the live site, but not on a test app.

Comparing enums to a traditional constant you might have:

public static int kDevApp = 0 ;
public static int kTestApp = 1 ;
public static int kLiveVersion = 2 ;

and then somewhere you have:

public class MyApp {
setAppVersion(int version) {
m_version = version ;
}

boolean takeRealCreditCards() {
switch (m_version) {
case kDevApp:
case kTestApp:
return false ;
case kLiveVersion:
return true ;
default:
return true ;
}
}
Now you can call
setAppVersion(kLiveVersion) and all is good.
But you can also call:
setAppVersion(4) <-- oops 4 isn't legal but our code runs and does who knows what?

With an enum this could now become:

public enum ValuesAppVersion {
kDev(0, false),
kQaTest(1, false),
kLive(2, true);

private final int dbValue;
private final boolean takeCreditCards ;

private ValuesAppVersion(int dbValue, boolean cc) {
this.dbValue = dbValue;
this.takeCreditCards = cc ;
}

public boolean takeRealCreditCards() {
return this.takeCreditCards() ;
}
}

now setAppVersion(kLive) works (it takes a ValuesAppVersion instance now) but setAppVersion(4) fails (won't compile)

Also if you add a new value to the enum, you don't need to remember to add the constant into the switch statement for the old takeRealCreditCards() , because there is no switch statement.

Enums rock :)

Doug
0
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.