Enum inheritance

Fancy enums with inheritance? Let’s take a look.

Let’s say we have two enums, like so:

Now, for some intelligent reason, we want to list all periods in either of these enums that have an odd number of days. Sounds very useful, doesn’t it?

How can we do this? A couple of loops? Sure! But that is boring. Instead, we decide it’s time to use some fancy Java. Let’s add an interface:

Mmmhmm, just right. Now we implement it on both enums:

Perfect! Let’s write the main class like so:

See? Not difficult at all 🙂 And that’s all for…

We aren’t done yet!

…you again!? OK, right, there is no inheritance. Right.

As anyone can see, the enums have a slight problem: leap years. It’s always the leap years…
So, let’s change the length() methods:

Umm…wait, where is the isLeapYear() method defined?

Ha! I was waiting for that! It’s in the interface!

There! Now we have two enums inheriting from a common interface.

Try running this, and also change the isLeapYear() method to return Year.of(2000).isLeap() instead, and see what happens.

2 thoughts on “Enum inheritance

  1. Reply

    removalists hobart

    Great blog here! Also your site loads up
    very fast! What host are you using? Can I get your affiliate link to your host?
    I wish my web site loaded up as fast as yours lol

    1. Reply

      tomas Post author

      I’m using A Small Orange 🙂

      Here is my affiliate link:

      And by the way, thanks 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Please answer this amazingly complicated math question to prove that you are not a spam bot: