Instance variable
In class-based, object-oriented programming, an instance variable is a variable defined in a class (i.e., a member variable), for which each instantiated object of the class has a separate copy, or instance. An instance variable has similarities with a class variable,[1] but is non-static. An instance variable is a variable which is declared in a class but outside of constructors, methods, or blocks. Instance variables are created when an object is instantiated, and are accessible to all the constructors, methods, or blocks in the class. Access modifiers can be given to the instance variable.
An instance variable is not a class variable, although there are similarities. It is a type of class attribute (or class property, field, or data member). The same dichotomy between instance and class members applies to methods ("member functions") as well; a class may have both instance methods and class methods.
Each instance variable lives in memory for the lifetime of the object it is owned by.[2]
Variables are properties an object knows about itself. All instances of an object have their own copies of instance variables, even if the value is the same from one object to another. One object instance can change values of its instance variables without affecting all other instances. Instance variables can be used by all methods of a class unless the method is declared as static.[3]
Example
C++
struct Request {
static int count1; // variable name is not important
int number;
Request(); {
number = count1; // modifies the instance variable "this->number"
++count1; // modifies the class variable "Request::count1"
}
};
int Request::count1 = 0;
In this C++ example, the instance variable Request::number
is a copy of the class variable Request::count1
where each instance constructed is assigned a sequential value of count1
before it is incremented. Since number
is an instance variable, each Request
object contains its own distinct value; in contrast, there is only one object Request::count1
available to all class instances with the same value.
Python
class Dog:
def __init__(self, breed):
self.breed = breed # instance variable
# dog_1 is an object
# which is also an instance of the Dog class
dog_1 = Dog("Border Collie")
In the above Python code, the instance variable is created when an argument is parsed into the instance, with the specification of the breed positional argument.
References
- "The Java Tutorial, Variables". docs.oracle.com. Oracle. Archived from the original on 23 October 2014. Retrieved 23 October 2014.
- "The Java Tutorials, Understanding Class Members". docs.oracle.com. Oracle. Archived from the original on 11 October 2014. Retrieved 23 October 2014.
- Matuszek, David. "Static". cis.upenn.edu. University of Pennsylvania. Archived from the original on 23 October 2014. Retrieved 23 October 2014.