Adding states and behaviors to enum constants

You can add states and behaviors to enum constants by defining instance variables and methods in an enum. All of these are accessible by the enum constants. Let's modify the Size enum defined in the previous section, by adding a state and behavior to it. Each enum constant can define a constant, specific class body, define a new state and behavior, or override the default behavior of the enum methods in which it is defined. The following is an example of this:

enum Size { 
    SMALL(36, 19), 
    MEDIUM(32, 20) {               // Constant specific class body  
        int number = 10;                    // variable specific to 
//MEDIUM int getSize() { // method specific to
//MEDIUM return length + width; } }, LARGE(34, 22) { @Override public String toText() { // overriding method toText
//for return "LARGE"; // constant LARGE } }; 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 getLength() { // method accessible to all
//enum return length; // constants } int getWidth() { // method accessible to all
//enum return width; // constants } public String toText() { // method accessible to all
//enum return length + " X " + width; // constants } }

In the preceding example, the Size enum defines three enum constants—SMALL, MEDIUM, and LARGE. It also defines instance variables (length and breadth), a constructor, and the getLength(), getWidth, and toText() methods.

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

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