-4

Here is a java code:

public class GusseGame {
    Player p1;
    Player p2;

    public void startgame() {
        p1 = new Player();
        p2 = new Player();
    }
}

Can I instead do this?

public class GusseGame {
    public void startgame() {
        Player p1 = new Player();
        Player p2 = new Player();
    }
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • 3
    You can, but it does something different: the first one defines fields (i.e. each object has `p1`and `p2`). The second one creates local variables `p1` and `p2` that only exit while `startgame` is running. – Joachim Sauer Dec 25 '20 at 19:55
  • Where are the close brace brackets? `}` – Yetti99 Dec 25 '20 at 19:58

1 Answers1

0

Variables only are not visible outside the scope where the are declared. If they are not persisted in some way, they are gone when the scope closes. Typically the scope is defines as the closest enclosing curly brackets {}.

So, in the first example, p1 and p2 are visible in the class GuessGame since it's the class curly brackets that enclose them.

In the second example, they are declared within the method startgame() and so are not visible outside the method.

DarkMatter
  • 1,007
  • 7
  • 13