I came across the code of guessgame
. There is a code snippet where three player objects are initialized the following way:
public class guessgame{
Player p1;
Player p2;
Player p3;
public void startGame() {
p1 = new Player();
p2 = new Player();
p3 = new Player();
...
}
...
}
The same worked when I declared and initiated it the following way as well.
public class GuessGame {
Player p1 = new Player();
Player p2 = new Player();
Player p3 = new Player();
public void startGame(){
...
}
...
}
Is there a difference between the two? In the first example, why was the three instance variables declared outside the startgame() method, and does it really matter internally?
Java offers two types of initializers, static and instance initializers.
The syntax for an initializer is the type, followed by the variable name, followed by an equal sign, followed by an expression. That expression can be anything, provided it has the same type as the variable. In this case, the expression is 10, which is an int literal. We can use more complicated expressions.
Is there a difference between the two?
Yes. The code in the first snippet will execute only in the context of startGame
. If you do not call startGame
, the objects would remain null
. Every time you call startGame
, the old objects, if any, would be discarded, and replaced with new ones.
The second snippet would execute once for each GuessGame
object when you call any of its constructors. The code would be shared among all constructors.
In the first example, why was the 3 instance variables declared outside the
startGame()
method
The only way to declare an instance variable is to do it outside a method. Variables declared inside a method are locals.
Another difference between the first and the second way is that calling instance methods that access players becomes "legal" only after calling startGame
in the first code snippet.
If you initialize outside the method, then it is executed when the class is instantiated and memory is allocated for them. If you don't, it just gets a null (or default value for primitives) assigned to them.
If you never call startgame(), then you're delaying allocating it, and perhaps the user never wants to start the game. This is smart if the players take a lot of memory to build, and you don't want the user to wait for that to happen (memory allocation), and just run methods immediately (that don't use them).
If for some reason you have several methods that need to use the p1, p2, p3 variables, then coordination of who will initialize may be confusing, so you just might bite the bullet and initialize them upfront. If you know there will be 3 players, why bother the methods with it? Otherwise you'll have to do something like:
if (p1 == null){
p1 = new Player();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With