What is the difference between a static variable and an instance variable in OOP?

Object Oriented Programming Questions



47 Short 36 Medium 25 Long Answer Questions Question Index

What is the difference between a static variable and an instance variable in OOP?

In Object-Oriented Programming (OOP), the main difference between a static variable and an instance variable lies in their scope and memory allocation.

A static variable, also known as a class variable, is shared among all instances of a class. It is declared using the "static" keyword and is stored in a common memory location. This means that any changes made to a static variable will be reflected in all instances of the class. Static variables are accessed using the class name, rather than through an instance of the class.

On the other hand, an instance variable, also known as a non-static variable, is unique to each instance of a class. It is declared without the "static" keyword and is allocated memory separately for each object. Each instance of the class has its own copy of the instance variable, and changes made to it will only affect that specific instance.

In summary, the key differences between a static variable and an instance variable in OOP are:
- Scope: Static variables are shared among all instances of a class, while instance variables are unique to each instance.
- Memory allocation: Static variables are stored in a common memory location, whereas instance variables are allocated memory separately for each object.
- Access: Static variables are accessed using the class name, while instance variables are accessed through an instance of the class.