b0bz
b0bz

Reputation: 2200

Java enum function return value

I'm trying to make a simple script that will return the velue of an enum, let's just give an example: //EG.class (should return the Animal ID.

import Object.Animal;

public class EG {
    public void main() {
        Animal AnimalID = Object.Animal.CAT;

        System.out.print(AnimalID);
        //Should return value of CAT: 2000 (long)
        //But I can't figure out what's wrong.
    }
}

//Object.class

public class Object {
    public enum Animal {
        CAT(2000L), DOG(2001L), MONKEY(2002L), TIGER(2003L);

        private long animal;

        private Animal(long a) {
          animal = a;
        }

        public long getAnimal() {
          return animal;
        }
    }
}

Upvotes: 1

Views: 9322

Answers (2)

Amir Afghani
Amir Afghani

Reputation: 38531

Why not just create a toString() method on the Animal enum?

public enum Animal {
    CAT(2000L), DOG(2001L), MONKEY(2002L), TIGER(2003L);

    private long animal;

    private Animal(long a) {
      animal = a;
    }

    public long getAnimal() {
      return animal;
    }

    @Override
    public String toString() { 
       return this.name() + ": " +animal;
    }
}

Upvotes: 6

Alexey Ogarkov
Alexey Ogarkov

Reputation: 2916

You need to call System.out.print(AnimalID.getAnimal());

Upvotes: 10

Related Questions