简体   繁体   中英

Java object scope, referencing from a method

I'm having some trouble getting scope right in my head. I understand why the code below won't work, but I don't understand conceptually how I should be doing it.

public class Game {

    private String playerName = "";
    private int numberOfPegs = 0;
    private boolean gameRunning = "True";


    public static void main(String[] args) {

        Game game = new Game();
        game.setupGame();
        game.playGame();
    }

    public void setupGame() {

        Display display = new Display();
        Code code = new Code();
        display.showGreeting();
        playerName = display.getUserInput("Enter your name: ");
        numberOfPegs = Integer.parseInt(display.getUserInput("How many pegs would you like?"));
        code.generateNewCode(numberOfPegs);
    }

    public void playGame() {
        String result = display.getGuess();

    }
}

I know why I can't call display.getGuess() from playGame() , it's because display is out of scope. I don't understand how to do this correctly. Do I create a new instance Display() for that method, that just doesn't feel like it's correct. I feel like I'm missing a Object Oriented concept when it comes to working with multiple objects.

Set the display as an instance field, and then initialize it in the setupGame() method.

private String playerName = "";
private int numberOfPegs = 0;
private boolean gameRunning = "True";
private Display display;


public static void main(String[] args) {

    Game game = new Game();
    game.setupGame();
    game.playGame();
}

public void setupGame() {

    display = new Display();
    Code code = new Code();
    display.showGreeting();
    playerName = display.getUserInput("Enter your name: ");
    numberOfPegs = Integer.parseInt(display.getUserInput("How many pegs would you like?"));
    code.generateNewCode(numberOfPegs);
}

public void playGame() {
    String result = display.getGuess();

}

There's no need to instantiate a member when you declare it. When you declare a member without instantiating, it takes its default value; 0 for numeric types, false for boolean and null for Object types. So in this case,

private int numberOfPegs = 0;

Would be the same as:

private int numberOfPegs;

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