Java enums: Gathering info from another enums

Posted by Samuel Carrijo on Stack Overflow See other posts from Stack Overflow or by Samuel Carrijo
Published on 2010-03-23T23:00:56Z Indexed on 2010/03/23 23:03 UTC
Read the original article Hit count: 680

Filed under:
|

I made a similar question a few days ago, but now I have new requirements, and new challenges =). As usual, I'm using the animal enums for didactic purposes, once I don't want to explain domain-specific stuff

I have a basic enum of animals, which is used by the whole zoo (I can add stuff to it, but must keep compatibility):

public enum Animal {
  DOG,
  ELEPHANT,
  WHALE,
  SHRIMP,
  BIRD,
  GIRAFFE;
}

I need to categorize them in a few, non-related categories, like gray animals (whale (my whale is gray) and elephant), small animals (bird, shrimp and dog), sea animals (whale and shrimp).

I could, as suggested in my previous questions, add a lot of booleans, like isGray, isSmall and isFromSea, but I'd like an approach where I could keep this somewhere else (so my enum doesn't need to know much). Something like:

public enum Animal {
  DOG,
  ELEPHANT,
  WHALE,
  SHRIMP,
  BIRD,
  GIRAFFE;

  public boolean isGray() {
    // What comes here?
  }
}

Somewhere else

public enum GrayAnimal {
  WHALE,
  ELEPHANT;
}

How is this possible? Am I requesting too much from Java?

© Stack Overflow or respective owner

Related posts about java

Related posts about enum