Instance variable

From Wikipedia, the free encyclopedia
Jump to: navigation, search
Not to be confused with Class variable.

In object-oriented programming with classes, 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 is similar to and contrasts with a class variable.[1]

An instance variable is not a Class variable. 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 class variable and instance variable you invoke with the object lives in memory for the life of that object.[2]

Instance 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[edit]

struct Request {
 
    static int count;
    int number;
 
    Request() {
        number = count; // modifies the instance variable "this->number"
        ++count; // modifies the class variable "Request::count"
    }
 
};
 
int Request::count = 0;

In this C++ example, the instance variable Request::number is a copy of the class variable Request::count where each instance constructed is assigned a sequential value of count 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::count available to all instances with the same value.

References[edit]

  1. ^ "The Java Tutorial, Variables". docs.oracle.com. Oracle. Archived from the original on 23 October 2014. Retrieved 23 October 2014. 
  2. ^ "The Java Tutorials, Understanding Class Members". docs.oracle.com. Oracle. Archived from the original on 11 October 2014. Retrieved 23 October 2014. 
  3. ^ Matuszek, David. "Static". cis.upenn.edu. University of Pennsylvania. Archived from the original on 23 October 2014. Retrieved 23 October 2014.