tags:

views:

120

answers:

2

I'd like to know if it is possible in Java to nest Enums.

Here what i'd like to be able to do :

Have an enum Species made of CAT and DOG wich would grant me access to sub enums of the available CAT and DOG breeds. For example, i'd like to be able to test if wether a CAT or a DOG and if an animal is a PERSAN CAT or a PITBULL DOG. CAT and DOG breeds must be distinct enums ,i.e a CatBreeds enum and a DogBreeds enum.

Here is an example of access pattern i'd like to use :

Species :

  • Species.CAT
  • Species.DOG

Breeds :

  • Species.CAT.breeds.PERSAN
  • Species.DOG.breeds.PITBULL
+3  A: 

Wouldn't you be better doing this with inheritance? Cat and Dog would be subclasses of Species. Persion would be a subclass of Cat and Pitbull would be a subclass of Dog.

What are trying to achieve by wanting to use Enums?

Tarski
I only got 2 classes, and dont need the other ones. Using inheritance is a bit too verbose and prevent me to use "type" based criteria selection or "type and subtype" based criteria selection.
Mathieu
There is ] at the end of your link. Understand the selection word as filtering.
Mathieu
Thanks Mathieu. Corrected comment: Well, if "type"-based criteria selection is what I think it means, then this may be a code smell. See http://hanuska.blogspot.com/2006/08/swich-statement-code-smell-and.html
Bert F
A: 
public enum A {

    a1, 
    a2;

    public enum B {
        b1, 
        b2
    }
}

and so on...

thelost
Neat - it is a nested enum and it might be the best he gets. However, this gives "Species.breeds.PERSAN" instead of the "Species.CAT.breeds.PERSAN" that he wants.
Bert F