I am trying to implement the Factory Pattern/Method to create a new class but I keep getting a Null Pointer exception. I have stepped through the code and I can't seem to work out what it is.
public class RandomEnemy {
SpaceShipFactory theFactory;
private ArrayList<SpaceShip> enemyList;
public RandomEnemy(){
setFactory(new SpaceShipFactory());
}
public void createRandomEnemy(int i){
SpaceShip s;
s = this.theFactory.createShip(i);
enemyList.add(s);
}
public void setFactory(SpaceShipFactory theFactory){
this.theFactory = theFactory;
}
}
And the Factory Class:
public class SpaceShipFactory {
public SpaceShip createShip(int i){
SpaceShip s = null;
if(i == 1){
s = new SpaceShip(QuickLoad("battlecruiser"), 0, 0, 256, 256);
System.out.println("Result is battlecruiser");
}
else if(i == 2){
s = new SpaceShip(QuickLoad("battleshooter"), 0, 0, 256, 256);
System.out.println("Result is battleshooter");
}
else if(i == 3){
s = new SpaceShip(QuickLoad("battlestar"), 0, 0, 256, 256);
System.out.println("Result is battlestar");
}
return s;
}
}
When enemyList.add(s);
is run I get a Null Pointer Exception. Any ideas why this is happening? I feel like I am missing something pretty obvious.
Because you never initialize
enemyList
.You need a
enemyList = new ArrayList<Enemy>
somewhere.An additional note: using
int
variables as magic numbers is not a good idea. Use a customenum
(which could also contain many ship specific data to avoid having a factory at all), for example: