This a topic everybody runs into while learning to code, and that sometimes brings some confusion into this process. Although as confusing as it may seem, it is also quite simple, and learning it can help you take your coding to another level.
What are instance and Class Variables?
A class variable is a variable defined in a class body that can be interacted with without an instance of such class. Class variables are shared among all instances of the class and its subclasses.
An instance variable is also a variable defined in a class body but belongs to a specific instance. Its value is not shared between instances of a class or its subclasses. Let say that each instance has variables with the same name but refer to different values.
Let's explore how class variables behave in Java with the following example.
As you can see the classes Goblin and Troll inherit from the class Monster which has a count class variable that is incremented every time a Goblin or a Troll created. Let’s create some of them and see the behavior
As you can see whenever a monster was created the Class variable count in the Monster class was increased. Since we created 2 monsters its value was 2 and we could access its value using the name of the class directly without the need for an instance. Although using an instance of any of these classes to access this variable will produce the same result.
A good use case for class variables following the previous example would be to imagine you are creating a video game in which you spawn different kinds of monsters on a field and the clearing condition is to kill all of them. How would you do that? You could keep track of the number of monsters spawn with a class variable and decrease its value whenever a monster is slain until it reaches zero.
Let’s explore the behavior of instance variables this time.
I modified the previous example and added an instance variable attack the would reflect the attack power of our monster. Let’s try using it.
As you can see the attack power of both is different even though they are sharing the same name variables and accessor methods name. If try to access this variable as a class variable you will see the following error.
Since its value belongs to a specific instance and not the class.