March 2019
Intermediate to advanced
242 pages
6h 21m
English
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 ...Read now
Unlock full access