Can I add a function to enums in Java?

I have an other option:

public enum Animal {
    ELEPHANT {
        @Override
        boolean isMammal() {
            return true;
        };
        @Override
        boolean isReptile() {
            return false;
        }
    },
    SNAKE {
        @Override
        boolean isMammal() {
            return false;
        };
        @Override
        boolean isReptile() {
            return true;
        }
    };

    abstract boolean isMammal();
    abstract boolean isReptile();
}

No need of external Interface and I am quite sure (did not test) it works also on Java7.


Yes, you can. It would 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 like:

Animal.ELEPHANT.isAmphibian()


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 make that an Enum as well 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 important to make any instance variable final as well.

You can find more details about it in the Java Language Specification.