Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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);
share|improve this question

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.

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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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