In object-oriented programming languages, there are three types of variables:
- Local Variables
- Static Variables
- Instance Variables
The local variables are the ones that are declared inside a function and cannot be accessed outside of the scope of that function. The scope of a local variable starts from where it is defined inside a function and ends where the scope of the function ends. This type of variable is not specific to object-oriented programming. The other two are specifically related to object-oriented concepts. So, in this article, we are going to what static and instance variables are and what is the difference between them.
A static variable is an instance variable that is associated with the class rather than the object of the class. These variables do not need to be called with the instance of the class. They are declared using the "static" keyword. The syntax for declaring this type of variable is as follows:
static data_type variable_name = value;
An instance variable is a member variable that is declared inside a class and cannot be accessed without creating an instance. The instance variables do not have any existence unless an object of the class is not declared. The syntax for declaring an instance variable is as follows:
access_modifier data_type variable_name;
The access _modifier in the above syntax refers to limiting the access to the variable. There are many access_modifiers but the most commonly used are public, private, and protected. If it is private, the instance variable cannot be accessed outside of the class. If it is public, it can be accessed from anywhere throughout the program. If it is protected, it can be accessed from a class itself and its child class.
Difference between Static Variable and Instance Variable
A static variable can be accessed with the class name whereas the instance variables are accessed with an object name.
A static variable can be accessed from the static or the non-static method whereas an instance variable cannot be accessed from the static method.
When we use a static variable, less memory is used by the program, whereas the instance variables use more memory.
Instance variables are created separately for each object whereas a static variable is shared among all the instances of a class.
Static variables act like global variables and are available to all the methods, and instance variables act like local variables.