简体   繁体   中英

Getting Null Pointer Exception with Factory Method

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 custom enum (which could also contain many ship specific data to avoid having a factory at all), for example:

enum ShipType
{
  BATTLE_STAR("battlestar"),
  BATTLE_CRUISER(battlecruiser"),
  BATTLE_SHOOTER("battleshooter",

  public final String name;

  private ShipType(String name) { this.name = name; }
}

class SpaceShip
{
  ShipType type;
  ...
}

First of all enemyList is not initialised. And if i value is not among {1,2,3} you are returning 's' which is reference variable of SpaceShip and which is not instantiated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM