Using inheritance with enum constants

The following is another example of an enum, that works with a set of subclasses by passing instances of subclasses to the enum constructor. To get the point across, I've modified the Size enum, which we have been working on with since the beginning of this chapter. The following is the modified code:

class Measurement {}                      // base class 
class Small extends Measurement {         // derived class 
    String text = "Small";                // state specific to class 
//Small } class Medium extends Measurement { // derived class public int getLength() { // behavior specific to class
//Medium return 9999; } } class Large extends Measurement {} // derived class enum Size { SMALL(new Small()), // constant created using Small
//instance MEDIUM(new Medium()), // constant created using Medium
//instance LARGE(new Large()); // constant created using Large
//instance private Measurement mObj; // Measurement is base class of // classes Small, Medium & Large Size(Measurement obj) { // wraps Measurement instance as an
//Enum instance mObj = obj; } Measurement getMeasurement() { // get the wrapped instance return mObj; } }

Again, you can't access the state and behavior of the enum-constant-specific code. The following is an example:

class Test1 { 
    public static void main(String args[]) { 
        var large = Size.LARGE; 
        System.out.println(large.getMeasurement()
.getLength()); // doesn't compile // the type of the
// variable used // to wrap the value
// of enum // constant is
// Measurement } }

Here, the enhanced enums come to the rescue. JEP 301 introduced enhanced enums by adding type variables or generics to it. Let's look at how it works in the next section.

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

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