2

I'm creating a simple game for my coursework. I have an array list containing different types of enemies made from different classes I have created. All the objects have a method called drawEnemy which draws the object to the screen (so the function drawEnemy() is in every class). I am trying to draw all the objects in the array in the draw loop.

ArrayList<Object> enemies;

enemies.add(new enemy1())
enemies.add(new enemy2())
enemies.add(new enemy3())

void draw(){
    for(Object i : enemies)
      i.drawEnemy();
}

This tells me that the function drawEnemy does not exist.

1
  • 1
    Remember, generics is for when you don't want just Object. Everything is, by definition, an extension of Object. You want an ArrayList<Enemy>, and then iterate using for(Enemy e: enemeies). Now you can call any method you defined in your Enemy class, because the compiled knows those methods exist. But don't give Enemy a method drawEnemy, just call it draw: we already know it draws an enemy, adding an echo just adds an echo. Commented Jan 1, 2020 at 19:36

1 Answer 1

1

You've defined enemies as an ArrayList<Object>, meaning that iterating over it will return Object references (regardless of the actual runtime types).

If you want to iterate over a list of enemies like this, you should extract a common interface or base class for all the enemy classes, and use it for the list type:

public interface Enemy {
    void drawEnemy();
}

public class Enemy1 implements Enemy {
    // code...
}

public class Enemy2 implements Enemy {
    // code...
}

public class Enemy3 implements Enemy {
    // code...
}

ArrayList<Enemy> enemies;
// list is then initialized and populated as it was

void draw() {
    for (Enemy i : enemies) // Note the i is defined as an Enemy
      i.drawEnemy();
}
Sign up to request clarification or add additional context in comments.

3 Comments

The problem with that is the enemies are of different object types. I have used different classes to create different types of enemies, so enemy1 will be one class and enemy2 will be another.
@Tahseen arg, missed that in the original question, mea culpa. See my edited answer.
Thanks man been trying to figure this out all day. Would this work if I used extends instead of implements? what is the difference between the two?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.