Two different types of variables connected to a class and their distinction. The factors are:
- Instance variable
- Class variable
Instance variables
Instance variables are those for which the value of the variable differs for each individual instance. We can additionally state that every object we create has a unique value. A few variables are also defined along with a class when it is created. As an illustration, we established a class called Students and specified a variable age. Since no two students in a class may have the same age, we gave the variable an average age of 16. The value of age will now print as 16 whenever we use an object to print that information. We are allowed to update the age value, but doing so would define a new instance variable for the particular object we are updating it for.
The code to change an object’s age will look something like this:
Std1.age = 18
Instance variables are produced when an object is formed with the new keyword. When the object is destroyed, they are also destroyed.
Static variables are created at program startup and discarded at program termination. By calling the variable name inside the class, one can access instance variables. ObjectReference.VariableName.
The variable is duplicated for each instance of the class. The other instances of that class are unaffected by changes made to the variable.
Class variable
“Class attributes are directly owned by the class, therefore they are not connected to any particular object or instance.”
The class variable, in this case Student, can be used to alter every instance’s age from 16 to 17 in the same way as in the example before.
“It is important to note that changing the value of the class variable will not affect the object’s instance variables, as in the example above.”
The following is the code to modify age using a class variable:
Students.age = 18
Static variables are created at program startup and discarded at program termination. You can invoke a class name to retrieve a static variable. ClassName.VariableName. Each instance of the class has access to a single copy of that variable. All other instances will be impacted if that variable is changed.