Home » Java » java – How do you use an object type as a parameter for method/constructor?-Exceptionshub

java – How do you use an object type as a parameter for method/constructor?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m currently working on a Java TD game. I have a class called “Wave” that holds the enemy types to spawn (that all extend the class “Enemy”) and the delay between the spawns.

public class Wave {

*I dunno what*[] enemyTypes;
int[] delays;
private Point spawnPoint;

Wave(*I dunno what*[] enemyTypes, int[] delays, Point spawnPoint) {

    this.enemyTypes = enemyTypes;
    this.delays = delays;
    this.spawnPoint = spawnPoint;

}

void spawnWave() {

    for (int i = 0; i < enemyTypes.length; i++) {

        try {

            Thread.sleep(delays[i]);

        } catch (InterruptedException e) {
          e.printStackTrace();
        }

        Point sP = new Point(spawnPoint);

        *The enemy type to spawn* enemy = new *The enemy type to spawn*.spawn(sP);

    }

}

}

I don’t know how to code the bits within the **

How to&Answers:

What about something like this?

You can get more information at Oracle Java Documentation

public class Wave<T extends Enemy> {

  List<T> enemyTypes;
  int[] delays;
  private Point spawnPoint;

  Wave(int[] delays, Point spawnPoint) {

    this.enemyTypes = new ArrayList<>();
    this.delays = delays;
    this.spawnPoint = spawnPoint;

  }

  boolean addEnemy(T enemy) {
    if(enemyTypes.contains(enemy)) {
      return false;
    }
    this.enemyTypes.add(enemy);
    return true;
  }

  void spawnWave() {

    for (int i = 0; i < enemyTypes.size(); i++) {

        try {

            Thread.sleep(delays[i]);

        } catch (Exception e) {}

        Point sP = new Point(spawnPoint);

        Enemy enemy = enemyTypes.get(i);
        enemy.spawn(sP);

    }
  }
}

Answer:

looks like a use case for factory pattern
you can provide array of factories for your enemy classes