I am developing a game in Java, and I am trying to create enemies that can shoot projectiles. I am defining the base class for all enemy types, and I have already defined a projectile class. What I would like to do is define a class type variable in the base enemy class, and a shootProjectile() method that will create a new instance of the defined projectile class when called. Pseudo code:
public class EnemyClass extends GameCharacter {
protected Class projectileType;
protected int a;
protected int b;
// Constructor and other stuff here
public void shootProjectile() {
projectileType newProjectile = new projectileType(a, b);
}
}
public class MyEnemySubClass extends EnemyClass {
public MyEnemySubClass() {
super();
projectileType = MySuperProjectile;
}
// Rest of class stuff here
}
public class MySuperProjectile extends Projectile {
public MySuperProjectile(parameter a, parameter b) {
// Constructor stuff using a and b
}
// Other projectile-related stuff
}
The idea of course is that in the enemy sub classes all I need to do is define what class of projectile they shoot, and the shootProjectile() method in the base class will do the rest.
I'm not sure how to achieve this. I have looked at defining generics but not sure how to make this work for my purposes and I'm not sure I fully understand how they work. Is something like this even possible in Java, or would I need to override shootProjectile for each subclass of EnemyClass to create their own projectile while attacking?
Thanks in advance!
Class.newInstance(). Also, useClass<? extends Projectile>so you can put thenewInstancein a reference ofProjectile