Using the static keyword in Java to increment an object index number
In this article I will show how to use Java's static keyword to increment a unique index number for object instances.
We will start by creating a simple class called Employee comprising fields only for name and address. These fields will be normal instance variables:
The Employee class defines two instance variables for the fields name and address, along with a constructor requiring these values and getters and setters. A toString() method is provided since this is good practice for most Java classes.
Being instance variables, the fields name and address can have individual values for each object instance of Employee that is created, as demonstrated below:
If you were to call the getName() method on object emp1 it would return "Fred", while calling getName() on emp2 would return "Barney".
The static keyword
The purpose of the Java static keyword is define a variable whose value is shared among all instance variables. That is, each object instance will have the same value at any point in time. If the static variable's value is changed by any one object instance then that change is automatically reflected in all the instances.
Let's define an integer static variable in Employee called nextIndex and set it to have a value of 1.
The purpose of nextIndex is to help us generate the next available number for the object instance, so we need to declare another instance variable to store this. We will call this index:
In the constructor we can set index to the current value of the static nextIndex, followed by incrementing the value of nextIndex ready for the following time the constructor may be called:
You can see this above with Employee.nextIndex
Finally, we will change the toString() method to include the index field so we can more easily verify that it is working:
Testing the code
Testing that our code works is straightforward. We can just instantiate a number of Employee objects and output their toString() results. Each new instance will have its index value one more than the previous:
The above should result in the following output:
Each time a new Employee instance is created, its index value will be incremented for you.