Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

java - How to nest an Enum inside the value of an Enum

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...