简体   繁体   English

Java对象范围,从方法引用

[英]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. 我知道为什么不能从playGame()调用display.getGuess() playGame() ,这是因为显示超出了范围。 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. 我是否为该方法创建了一个新的实例Display() ,只是感觉不正确。 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. display设置为实例字段,然后在setupGame()方法中对其进行初始化。

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. 对于数字类型为0 ,对于boolean类型为false ,对于Object类型为null So in this case, 所以在这种情况下

private int numberOfPegs = 0;

Would be the same as: 将与以下相同:

private int numberOfPegs;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM