In my game when pressing the right mouse button you will place an object on the ground. all objects have the same super class (GameObject). I have a field called selected and will be equal to one certain gameobject at a time. when clicking the right mouse button it checks whats the instance of selected and that how it determines which object to place on the ground. code exapmle: t is the "slot" for which the object will go to.

if (selected instanceof MapleTree) {
    t = new MapleTree(game,highLight);
} else if (selected instanceof OakTree) {
        t = new OakTree(game,highLight);

Now it has to be a "new" instance of the object. Eventually my game will have hundreds of GameObjects and I don't want to have a huge if else statement. How would I make it so it scrolls though the possible kinds of objects and if its the correct type then create a new instance of it...?

When pressing E it will switch the type of selected and is an if else statement as well. How would I do it for this too? here is a code example:

if (selected instanceof MapleTree) {
        selected = new OakTree(game);
} else if (selected instanceof OakTree) {
    selected = new MapleTree(game);

What about making clones or factories?

For clones, you could just call object.clone(). This would make another instance of this object type. Though I'm not sure if they will share references, so may not be the best way.

Thinking a little more, I think you could use Java Reflection library.

Assuming you just have one constructor with no parameters, this could work:

Constructor ctor = selected.getClass().getDeclaredConstructors()[0];
t = (GameObject)ctor.newInstance();

If you have parameters for your constructor like in your example you can use something like this:

Constructor ctor = selected.getDeclaredConstructor(game.getClass());

But be aware that this may be slow. So there may be better options for this.

| improve this answer | |
  • \$\begingroup\$ How would I got to implement it here? its a lil hard for me to understand.. \$\endgroup\$ – Amit Assaraf Sep 26 '12 at 22:59
  • \$\begingroup\$ @gopgop See my edit. it explains clones, and how you could do it better with reflection. \$\endgroup\$ – Gustavo Maciel Sep 26 '12 at 23:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.