An example

Imagine limiting the sizes of a shirt to some predefined sizes (such as Small, Medium, and Large). The following code shows how you can do that with an enum (Size):

enum Size {SMALL, MEDIUM, LARGE}

Java's coding guidelines recommend using uppercase to define enum constants (such as SMALL). Multiple words in a constant can be separated by using an underscore.

The following code shows how you can use the Size enum in a class, Shirt, to restrict its sizes to constants defined in the Size enum:

class Shirt { 
    Size size;              // instance variable of type Size 
    Color color; 
 
    Shirt(Size size, Color color) {      // Size object with Shirt                                                                     
// instantiation this.size = size; this.color = color; } }

The instance variable of the Size type in the Shirt class limits the values that are assigned to it to Size.SMALL, Size.MEDIUM, and Size.LARGE. The following code is an example of how another class, GarmentFactory, uses enum constants to create instances of the Shirt class:

class GarmentFactory { 
    void createShirts() { 
        Shirt redShirtS = new Shirt(Size.SMALL, Color.red); 
        Shirt greenShirtM = new Shirt(Size.MEDIUM, Color.green); 
        Shirt redShirtL = new Shirt(Size.LARGE, Color.red); 
    } 
} 
Enums define new types with predefined sets of constant values. Enums add type safety to constant values.
..................Content has been hidden....................

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