Tuesday, November 13, 2007

Enums in Java 5

Some example uses of Java 5's enums. Shows that enums are types which can have data and behaviour. They are instantiated and can can be imported into other classes.

This class creates an enum with some instances.

package org.rbram.tests.enumtest;
public final class FruitEnum {
  public enum Fruit {
    // Instances of the enum as a comma separated list of constructor calls.
    Apple("red"), Banana("yellow"), Grape("green");

    // Enums can have instance variables.
    private String color;
    private int count;

    // Enums can have multiple constructors.
    Fruit(final String theColor) {
      this.color = theColor;
      this.count = 0;
    }

    // Enums can have behaviour
    public String getColor() {
      return this.color;
    }

    public int getCount() {
      return this.count;
    }

    public synchronized int addFruit(final int howMany) {
      this.count += howMany;
      return this.count;
    }

    public synchronized int takeFruit(final int howMany) {
      if (howMany > this.count) {
        this.count = 0;
      } else {
        this.count -= howMany;
      }
      return count;
    }
  }
}

This class imports and tests a few aspects of the enums.

package org.rbram.tests.enumtest;
import org.rbram.tests.enumtest.FruitEnum.Fruit;
public final class FruitTest {

  public static void main(final String[] args) {
    Fruit fruit = Fruit.valueOf("Apple");
    fruit.addFruit(23);
    System.out.println("I have " + fruit.getCount() + " " + fruit
        + "s, which are all " + fruit.getColor() + " in color.");

    fruit = Fruit.valueOf("Grape");
    fruit.takeFruit(12);
    System.out.println("I have " + fruit.getCount() + " " + fruit
        + "s, which are all " + fruit.getColor() + " in color.");

    try {
      // You have to get the id right or catch the runtime exception.
      fruit = Fruit.valueOf("Durian");
    } catch (IllegalArgumentException exception) {
      System.err.println("Could not find fruit named Durian.");
    }

  }
}

Output of running the above code.

I have 23 Apples, which are all red in color.
I have 0 Grapes, which are all green in color.
Could not find fruit named Durian.

Other Resources

No comments: