Global variables are declared outside of any function and are accessible by all functions. These variables are generally set to private.
In the past, we have created what is called local variables. These are variables declared inside of a function and are only accessible by that function.
Global variables are unique because every function/method we write can use the same one. Make it once, and use it everywhere in that class. We use global variables when we have a variable that needs to be used in the entire class.
For instance, in our Player class we are designing. The gamertag is better as a global variable because it makes sense we would need to know the players name in almost all of the methods for that class.
It may seem that local variables are no longer important, but often there are variables that are only needed inside of that specific function.
For instance, in our Player class we are going to write a method that saves the players score to a file. When we create a variable for that file it won’t need to be accessed anywhere but that method. So we will leave it local.
Instance variables are created from a class, a copy of its variables are made for each instance. These variables belong to their specific instance.
This way, if we create a player class with an instance variable for score, that variable will be separate for each player.
Class variables are the exact opposite of instance variables. This is a variable that belongs to the class. Only one copy of this variables exists for all instances. You must use the static keyword to create a class variable.
This way, if we have a class variable in the player class that keeps track of how many players are created, it’ll be the same value through all of the instances of player. So if I make a change to this variable in one instance, it is reflected in all.
When we send arguments to a constructor. Those variables are local variables. Therefore, if we write another method in our class and we want access to those arguments we can’t.
If we make a global variable and then set it equal to the arguments in the constructor, we are now giving those values access to the entire instance.
The this keyword comes in hand. Normally we would have to create two variables for this transfer. However, if we want we can give them the same exact name, but use the this keyword to refer to the variable from the class.
Using the code you had from last time, create global variables for gamerTag and for playerNumber.
Save the constructor arguments to each global variable and use the this keyword.
Create a class variable with static that keeps track of how many players were made.
In the constructor, increment this variable by one.