0

This was very difficult for me to word into a question so allow me to explain.

I have an abstract class Entity and subclasses House and Warehouse. Each subclass has the same static variables with different values.

When a button is pressed in my game an Action is created which specifies which Entity subclass gets created and placed in the world. I want to write a generic method to place some Entity to the world using the static variables of which ever subclass it is.

I have a class PlaceEntityAction and when the mouse is clicked the appropriate entity will be placed assuming conditions are correct. How can I pass the Class I want to be placed to this Action so it works with any generic Entity?

Here is some dumbed down code:

if (mousePressed)) { if (some conditions are true) { int ex = x pos int ey = y pos if (world.player.haveFunds(e.COST_ENERGY, e.COST_MONEY, e.COST_RESOURCE)) { if (world.places[ex][ey] == 0) { world.entities.add(e); world.player.addEnergy(-e.COST_ENERGY); } } } } 

So basically how can I get that e to be whatever subclass I pass to the Action since COST_MONEY, etc is static and should be accessed by the Class and not an object?

I'm really struggling to express what I want. Maybe someone can decipher this or provide some other insight regarding my issue. I can provide any other information necessary if you want.

EDIT:

e is an instance of whichever subclass I previously initialized based on an ID system but I don't like this method.

3
  • Your example is not really clear. What is e for example in your code? Commented Apr 17, 2013 at 18:00
  • Please be more clear , help us to understand. Commented Apr 17, 2013 at 18:02
  • You're looking for the factory pattern Commented Apr 17, 2013 at 18:05

2 Answers 2

4

Static variables are the wrong approach here, especially since you've already instantiated your entity.

Instead, create abstract functions costEnergy(), costMoney(), and so on on the parent class, and implement them (with the correct values) on the child.

Sign up to request clarification or add additional context in comments.

Comments

1

Static variables aren't polymorphic in Java. An option would be to declare abstract methods getCostEnergy, getCostMoney and getCostResource in Entity, and have each subclass override those methods to return different constants. Would that work for your scenario?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.