Enum: Behind the scenes

I’ve never really felt 100% comfortable using the enum type because of my lack of understanding how it is constructed . . .

. . . until now :grin:

Here is how a basic enum might be typically declared.

enum DevTalkForum {
   NEWS,
   CHAT,
   JOURNALS,
   BOOK_ERRATA
}

And here is the class that is constructed behinds the scenes:

final class DevTalkForum extends Enum<DevTalkForum> {

   /**
    *   the type Enum only has 2 simple properties: 
    */
   private DevTalkForum(String name, int ordinal) { 
      super(name, ordinal); 
   }

   /**
    *   each element in the enum is a subclass of the type Enum
    */
   public static final DevTalkForum NEWS = new DevTalkForum("NEWS", 0);
   public static final DevTalkForum CHAT = new DevTalkForum("CHAT", 1);
   public static final DevTalkForum JOURNALS = new DevTalkForum("JOURNALS", 2);
   public static final DevTalkForum BOOK_ERRATA = new DevTalkForum("BOOK_ERRATA", 3);

   /**
     *   all the enum classes are stored in an array
     */
   private static final DevTalkForum[] VALUES = { NEWS, CHAT, JOURNALS, BOOK_ERRATA };
   
   public static DevTalkForum[] values() { 
      return VALUES.clone(); 
   }
   
   public static DevTalkForum valueOf(String name) {
      for (DevTalkForum e : VALUES) 
         if (e.name().equals(name)) return e;
      throw new IllegalArgumentException();
   }
}

Realising how the enum is constructed has helped me understand how to use it correctly.
For example, the toString() of the class can be overridden to provide an alternative string value if you do not want to add another property.

enum DevTalkForum {
    NEWS,
    CHAT,
    JOURNALS,
    BOOK_ERRATA;

    @Override
    public String toString() {
        switch (this) {
            case CHAT:
                return "Chat";
            case JOURNALS:
                return "Journals";
            case BOOK_ERRATA:
                return "Book Errata";
            case NEWS:
            default:
                return "News";
            
        }
    }
}

So now that I feel closer to the enum I think I’m going to try and pop them into my code a bit more often.

Hope this was somehow helpful

1 Like

Corresponding tweet for this thread:

https://twitter.com/dev_talk/status/1351619447707099137

Share link for this tweet.


Related portal:

Nice one Finner :+1:

Funnily enough, I had to re-read the Enumerable and Enumerator chapter in The Well Grounded Rubyist (which I loved btw) a couple of times as it’s a little harder to grok than some of the other stuff. I’d actually like to read the book again one day as I loved it :smiley:

1 Like