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

前端 未结 5 894
攒了一身酷
攒了一身酷 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 05:55

    Note, I have already initialized board in the class Game so if I do it again, won't they be two totally different Board objects?

    Yes, you'll then have two totally different instances. You're getting the basic idea - you have instances of objects in your program and now you have to get them to work together.

    Now if I want to access the Square[][] through the object board (in Game) of type Board. Do I just declare a variable with the same name and type or do I have to initialize it again?

    You have 2 ways to give Game access to the squares (probably more than just 2 depending on how you look at it):

    1 Have the Board provide access to the Squares (e.g. a getter method on Board that returns the Squares array) so Game can access them. Board can then save the reference (have its own instance variable to hold the reference to squares, or can ask Board each time for the reference).

    2 Have the Board provide methods that do the things that Game wants to do on the the squares, i.e. the game asks the board to do something to the squares and the board does the action on the squares.

提交回复
热议问题