Examples from the past – changes to define enums

Prior to the introduction of enums, developers often used public, static, and final variables to define constants. The following is an example:

class Size { 
    public final static int SMALL = 1; 
    public final static int MEDIUM = 2; 
    public final static int LARGE = 3; 
}

The major drawback of using public, static, final, and int variables is type safety; any int value could be assigned to a variable of the type int, instead of the Size.SMALL, Size.MEDIUM, or Size.LARGE constants.

Java 5 introduced enums, an addition to the language construct, to enable developers to define an enumeration of constants. Here's a quick example:

enum Size {SMALL, MEDIUM, LARGE} 
class SmallTShirt { 
    Size size = Size.SMALL; 
    //..other code 
} 

With a variable of the type Size, an assignment is limited to the constants defined in Size. An enum is a perfect example of how language can simplify the implementation of a model, at the cost of certain constraints. Enums limit the extensibility to interfaces. Other than that, enums are full-fledged classes. As a developer, you can add states and behaviors to them. Another benefit is that an enum can also switch constructs, which was previously limited to primitives and a String class.

A new language construct is like a new human relationship, biological or otherwise. It has its own share of joys and sorrows.
..................Content has been hidden....................

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