Workarounds to access enum constants

One of the ways to access members such as variables and methods that are specific to an enum constant is—to define them for all members, but only allow the usage for specific members (I know, this is not recommended). I've removed code that is not relevant to show how this works, as follows:

enum Size {
SMALL(36, 19),
MEDIUM(32, 20),
LARGE(34, 22);
int length; // instance variable
//accessible
int width; // to all enum constants
Size(int length, int width) { // enum constructor; accepts
//length
this.length = length; // and width
this.width = width;
}
int getSize() {
if (this == MEDIUM)
return length + width;
else // throws runtime
// exception
throw new UnsupportedOperationException(); // if used with
// constants
} // other than
//MEDIUM
}

Let's try to access the method getSize() using enum constants:

System.out.println(MEDIUM.getSize());
System.out.println(LARGE.getSize());

The output of the preceding code is as follows:

52
Exception in thread—java.lang.UnsupportedOperationException

First and foremost, adding code (the getSize() method) that is not applicable to all enum constants breaks the encapsulation. In the preceding example, I defined getSize() in the main body, whereas only the MEDIUM enum constant required the getSize() method. This is neither desirable nor recommended.

Compared it with an arrangement of a base class and its derived classes, adding all of the behaviors specific to the different derived classes in your base class. However, it's not recommended as it doesn't define the encapsulated code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.198.81