简体   繁体   中英

Using another class variable

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.

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 NullPointerException s

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