Is it possible to add a function for listing in Java?

I have an enumeration that looks like

public enum Animal { ELEPHANT, GIRAFFE, TURTLE, SNAKE, FROG } 

and I want to do something like

 Animal frog = Animal.FROG; Animal snake = Animal.SNAKE; boolean isFrogAmphibian = frog.isAmphibian(); //true boolean isSnakeAmphibian = snake.isAmphibian(); //false boolean isFrogReptile = frog.isReptile(); //false boolean isSnakeReptile = snake.isReptile(); //true boolean isFrogMammal = frog.isMammal(); //false boolean isSnakeMammal = snake.isMammal(); //false 

I simplified the example for didactic purposes, but it would be really useful for my real life example. Can I do this in Java?

+48
java function enums
Mar 16 '10 at 18:32
source share
2 answers

Yes Enum is a class in Java:

 public enum Animal { ELEPHANT(true), GIRAFFE(true), TURTLE(false), SNAKE(false), FROG(false); private final boolean mammal; private Animal(final boolean mammal) { this.mammal = mammal; } public boolean isMammal() { return this.mammal; } } 

but in your case, for a real system, I would do it Enum, since there is a fixed set of types of animals.

 public enum Type { AMPHIBIAN, MAMMAL, REPTILE, BIRD } public enum Animal { ELEPHANT(Type.MAMMAL), GIRAFFE(Type.MAMMAL), TURTLE(Type.REPTILE), SNAKE(Type.REPTILE), FROG(Type.AMPHIBIAN); private final Type type; private Animal(final Type type) { this.type = type; } public boolean isMammal() { return this.type == Type.MAMMAL; } public boolean isAmphibian() { return this.type == Type.AMPHIBIAN; } public boolean isReptile() { return this.type == Type.REPTILE; } // etc... } 

Also note that it is also important to make any instance variable final .

+66
Mar 16
source share

Yes, you can. It will look like this:

 public enum Animal { ELEPHANT(false), GIRAFFE(false), TURTLE(false), SNAKE(false), FROG(true); private final boolean isAmphibian; Animal(boolean isAmphibian) { this.isAmphibian = isAmphibian; } public boolean isAmphibian() { return this.isAmphibian; } } 

Then you would call it the following:

Animal.ELEPHANT.isAmphibian()

+12
Mar 16 '10 at 18:35
source share



All Articles