-1

I'm having some trouble referencing to another class and retrieving a variable from it. I don't get any error but the app crashes on launch. I seem to do the exactly the same thing in other parts of my program without problem. But perhaps I'm missing something here. I have deleted code that doesn't have to do with this problem to make it easier to read. This code will not run for me:

package com.example.gamm;

public class HUD {
    static Game _game = null;
    HUD(){
        int textSize = _game.TEXT_SIZE;
    }
}

In the game class I have: private HUD _hud = null; before the constructor and _hud = new HUD(); inside the constructor. Not sure that that matters now but my end goal is to call a function inside HUD from the Game class.

So if I comment out the line int textSize = _game.TEXT_SIZE; or manually gives it a value it runs as it should. So the problem seems to be when using the _game variable to reference the other class.

Tlaloc-ES
  • 4,825
  • 7
  • 38
  • 84
Jakstb
  • 9
  • 2
  • You seem to be headed for a two-way dependency, I would pass one of those (ideally the "parent" object) through the constructor to the other class via `this`, so e.g. `new HUD(this)` while in the game class. – Rogue Feb 13 '19 at 14:40

1 Answers1

2

You never instantiate the _game field. This means that whenever you try to access one of it's underlying members you get a NullPointerException. You need to make sure _game is assigned to an instance of Game before trying to refer to it.

Please see this post for more info on NullPointerExceptions

Ferdz
  • 1,182
  • 1
  • 13
  • 31
  • That is very true, thanks. So I can use `_game = new Game();` in the HUD constructor. The Game() needs a context as input however so it seems tricky to do this. I have another class that is doing the same thing and that doesn't seem to instantiate the _game field. Is there some other way of going about it? – Jakstb Feb 13 '19 at 14:50
  • You mentioned that `Game` is the class that instantiates `HUD`. If that is the case why not pass that `Game` instance as a parameter to your `HUD` constructor like @Rogue suggested? – Ferdz Feb 13 '19 at 14:52
  • edit: So I found out it was a shared reference and I can instantiate it with `HUD._game = this;` inside the Game() constructor. Thank you for the help! – Jakstb Feb 13 '19 at 14:57
  • You can, but you probably should avoid `static` altogether in your case, since it's considered bad practice. However if your question is resolved don't forget to mark the response as accepted :) – Ferdz Feb 13 '19 at 15:01