The Secret Classes or How I Stopped Counting and Loved the Enumerator

View: 748    Dowload: 0   Comment: 0   Post by: naruto   Category: Java Sun   Fields: Other

This article will examine some of the uses that the enum type can be put to. I don't know about you, but I like using enumerators. The perceived usage of the enum type is that they provide a list of possible values and are required for the switch statement. That's it, right? Big wrong.

The enum type is a class. By remembering this, the extensibility of an enum is great. It can be used for a whole lot more than simply representing the fixed values for an attribute.

It's Objects All the Way Down

I'll start with a simple premise. An enum type defines a class that has a fixed number of instances. Like any class, there can be member variables and methods giving the whole Java world in a simple structure. Let's look at a simple example:

public enum Season
{
   SUMMER,
   WINTER,
   AUTUMN,
   SPRING
}

Here is a class, called Season, that has four fixed instances. It's important to remember this, as the fact that you have four objects is what gives the enum its simple structure and its amazing power. Power it is sworn to use for good.

A common use of enums is in switch statements such as this:

String getForcast(Season season)
{
  switch (season)
  {
     case SUMMER:
     {
        return "Sun, sun, sun";
     }
     case AUTUMN:
     {
        return "Cold and blustery";
     }
     case WINTER:
     {
        return "Snow and ice";
     }
     case SPRING:
     {
        return "Overcast with showers";
     }
  }
  return null;
}

"Hang on! The elements of the enumerator are all objects so can't they just have a method to return the forecast?" I hear you cry. Good spot. That is exactly the way to go. A member variable, a method, and a simple constructor, and off you go:

public enum Season {
   SUMMER("Summer", "Sun, sun, sun"),
   WINTER("Winter", "Snow and ice"),
   AUTUMN("Autumn", "Cold and blustery"),
   SPRING("Spring", "Overcast with showers");

   private final String seasonName;
   private final String forcast;
   private Season(String seasonName, String forcast)
   {
      this.seasonName = seasonName;
      this.forcast = forcast;
      System.out.println("Creating " + this);
   }
   String getForcast()
   {
      return this.forcast;
   }

   public String toString()
   {
      return seasonName + "{" + forcast + '}';
   }
}

I've included a friendly string description and overridden the method toString().

Now, instead of having to write a method outside of Season that takes a value as an argument, the values can be invoked directly to get the value:

String forcast = Season.WINTER.getForcast();

The Immutible Likeness of Being [An Enumeration]

If you're observant, the member variables are both marked final. This is not mandated but, and it's a big Jo-Lo one, it is definitely encouraged.

So each enumeration is an object and it can have variables, methods, the whole low-flying acrobatics team. These are not just objects, their special status means they must be treated as immutable objects. They're not quite immutable but it is a good perspective to take.

By being an enum, there is no need for the hashCode() and equals() methods. Each instance is unique and its equality is fixed. Because of this nature, it is recommended that you don't change their states.

You Want Functionality With That?

I've shown above the way that enum objects can have properties and methods. Sometimes the behaviour of an action must differ depending on the value of the enum. This can be achieved with an abstract method that is overridden by each enum or by having a functional class provide the behaviour.

The abstract method first:

public enum Season
{

   SUMMER("Summer", "Sun, sun, sun")
   {
      boolean willItRain()
      {
         return false;
      }
   },
   //...
   SPRING("Spring", "Overcast with showers")
   {
      boolean willItRain()
      {
         return true;
      }
   };

   //...

   abstract boolean willItRain();
}

This works but it isn't that extensible, and the enumeration class soon becomes clogged if you have just a few of the overrides. It is time to delegate the work to a functional class; enter the enumeration factory method.

We first move all the forecasting out of the enum class. We have a base, SeasonFunctions, that is abstract, and then four lovely children that can implement the functionality anyway they see fit:

 

abstract class SeasonFunctions {
   private final String seasonName;
   private final String forcast;

   SeasonFunctions(String seasonName,
         String forcast)
   {
      this.seasonName = seasonName;
      this.forcast = forcast;
      System.out.println("Creating " + this);
   }
   abstract boolean willItRain();
   abstract int dayTimeHigh();
   abstract int nightTimeLow();

      String getForcast()
   {
      return this.forcast;
   }

   public String toString()
   {
      return "SeasonFunctions{" + this.getSeasonName()  + "}";
   }

   String getSeasonString()
   {
      return this.getSeasonName() + "{" + this.getForcast() + '}';
   }

   private String getSeasonName()
   {
      return this.seasonName;
   }
}

The Secret Classes or How I Stopped Counting and Loved the Enumerator

This article will examine some of the uses that the enum type can be put to. I don't know about you, but I like using enumerators. The perceived usage of the enum type is that they provide a list of possible values and are required for the switch statement. That's it, right? Big wrong. The enum type is a class. By remembering this, the extensibility of an enum is great. It can be used for a whole lot more than simply representing the fixed values for an attribute.

Posted on 21-03-2014 

Comment:

To comment you must be logged in members.

Files with category

  • Very Basic Java Fighting Game

    Very Basic Java Fighting Game

    View: 50    Download: 4   Comment: 0

    Category: Java Sun     Fields: none

    Sharing you the source code of this simple fighting game created in java[eclipse]. You will learn character animation, basic interaction and some AI implementation. If you have some questions just spam me at mark[dot]cabalar[at]yahoo[dot]com. Visit...

  • Very Basic Java Game programming - Part 1

    Very Basic Java Game programming - Part 1

    View: 25    Download: 1   Comment: 0

    Category: Java Sun     Fields: none

    I don’t know how exactly to start or make an introduction for this post. I just made in to the concept of designing a simple fighting game tutorial - from doing the character animation to its overall functionality. This tutorial is intended for...

  • Recharge App (Like Paytm)

    Recharge App (Like Paytm)

    View: 31    Download: 2   Comment: 0

    Category: Java Sun     Fields: none

    Hello Dear, This is a recharge app you can recharge your mobile, electricity bill, insurance, gas bill, landline bill, etc. I have wallet functionality which you can add money in your wallet and recharge mobile using wallet amount. I have Admin...

  • Credit Card Number Verifier

    Credit Card Number Verifier

    View: 25    Download: 0   Comment: 0

    Category: Java Sun     Fields: none

    It's a JAVAFXML app that verifies if a number is a valid credit card number. It uses Luhn algorithm to verify. It also predicts the last credit card number given 15 numbers.

  • Cabin Assigner Pro

    Cabin Assigner Pro

    View: 31    Download: 0   Comment: 0

    Category: Java Sun     Fields: none

    This program allows to create and assign cabins at summer camp. There are error checking features including setting a capacity, an alert if a child is assigned to a cabin outside of their age range, it will prohibit assigned a cabin that is set for...

  • Java - Simple Phone Directory System

    Java - Simple Phone Directory System

    View: 47    Download: 1   Comment: 0

    Category: Java Sun     Fields: none

    Simple Phone Directory System using Java With MySql in Backend. Please make scan after download to secure if there is available viruses in the files.

  • Working from source project

    Working from source project

    View: 242    Download: 0   Comment: 0

    Category: Java Sun     Fields: Game - Entertainment

    Working with LibGDX source is relatively easy if you are comfortable with your IDE and maven/ant/gradle. Even if you aren't, this article can hopefully guide you along the way. There are two main components when working with the LibGDX, the java...

  • Running and Debugging a LibGDX project

    Running and Debugging a LibGDX project

    View: 132    Download: 0   Comment: 0

    Category: Java Sun     Fields: Game - Entertainment

    You can run and debug your projects from your IDE and command line, this article will go through the recommended ways to launch and debug your projects.

 
File suggestion for you
File top downloads
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd