This compiles fine:
static final Screen screen = Screen.getInstance();
static final InputListener listener = InputListener.getInstance();
static
{
screen.addListener(listener);
screen.setCurrentState(new MainMenu());
screen.setVisible(true);
}
private GameManager(){
mobs = new ArrayList<Mobile>();
player = new Player(100, 100);
mobs.add(player);
}
This doesn't:
static final Screen screen = Screen.getInstance();
static final InputListener listener = InputListener.getInstance();
private GameManager(){
mobs = new ArrayList<Mobile>();
player = new Player(100, 100);
mobs.add(player);
screen.addListener(listener);
screen.setCurrentState(new MainMenu());
screen.setVisible(true);
}
Throws: Exception in thread "main" java.lang.ExceptionInInitializerError saying:
Caused by: java.lang.NullPointerException
at main.pack.minerdude.GameManager.<init>(GameManager.java:42)
at main.pack.minerdude.GameManager.<clinit>(GameManager.java:10)
... 1 more
Line 10 is:
private static final GameManager manager = new GameManager();
Line 42 refers to "return manager":
public static GameManager getInstance(){
return manager;
}
Why is behaving like that if the static block gets generated after creating mob and adding player to it?
EDIT
So, this is my conclusion after executing this code and getting the following output:
GameManager constructor
Screen constructor
Screen getInstance
static of GameManager
GameManager GetInstance
Some class wants a GameManager object, so to return it it has to be created first.
GameManager has a Screen object declared static and has the same requeriments as the first step.
Screen get's created so GameManager has it's static object initialized and continues to initialize the following statics.
Now that GameManager it's fully initialized, it returns itself to the first caller.
One would assume that when GameManager getInstnace gets called, before calling it's constructor it would first initialize all it's statics, but it seems it doesn't work that way as the constructors get's called before any of it's statics. If I create a new GameManager directly - not using getInstance() - then the order is preserved: statics, variables, constructor then return.