Pushing objects from an abstract class' subclass to a stack using HashMap?

I am looking for a way to instantiate a subclass from an abstract class using a token from a hashMap and then push to my stack. Any insight would be appreciated

Barn class

 animalStack.push(new Animal("Cow"));      

Animal class:

abstract class Animal {
  Map<String, Object> m1 = new HashMap<String,Object>();
  {
    m1.put("Cow", new Cow());
  }

  abstract int age();
}

class Cow extends Animal {
    @Override
    int age() {
        return 0;
    }
}

For instance, I want the Cow object to be put into my animal stack.

Barn class: http://pastebin.com/4az10R8Q Animal class: http://pastebin.com/hh9t7yzw

Jon Skeet
people
quotationmark

Currently you can't instantiate a Cow - because doing so will create an Animal, which will in turn try to populate it map with another Cow etc. (In fact you can't create any Animal instances for the same reason.)

It sounds like your map should actually be static, and you should have a static factory method:

abstract class Animal {
  private static final Map<String, Animal> map
      = new HashMap<String,Object>();

  static {
    map.put("Cow", new Cow());
  }

  static Animal getAnimal(String name) {
    // TODO: Validation
    return map.get(name);
  }

  abstract int age();
}

Then you can use:

animalStack.push(Animal.getAnimal("Cow"));

Note that this will push a reference to the same object each time you call it - you might want your Animal.getAnimal method to create a new instance on each call.

people

See more on this question at Stackoverflow