Reference variable to an object instantiated/initialized in another class in Java

前端 未结 5 946
攒了一身酷
攒了一身酷 2021-01-25 05:41

The reason I\'m asking is because I\'m getting NullPointerException. I now this is very easy but I\'m pretty new programming and find this a bit confusing. So say I have initial

5条回答
  •  耶瑟儿~
    2021-01-25 06:03

    The instance of Board that you are creating in your main() method is not the same as the instance variable board of your View class. View has the following:

    public class View extends JFrame { 
      Board      board;
      ...
    

    This variable board is never assigned a value (i.e. a new Board())

    Then, in your Game class's main method, you declare a new Board and a new View:

    Board board = new Board();
    View view = new View();
    

    This variable board is a local variable of the main method, and has no relationship to the instance variable board in your View. In your View class, you need to change your variable declaration to be:

    Board board = new Board();
    

提交回复
热议问题