In object-oriented programming, an instance variable is a variable defined in a class (i.e. a member variable), for which each object of the class has a separate copy, or instance. An instance variable is similar to and contrasts with a class variable. A class variable is defined using the static declaration modifier in languages like Java, C#, and C++. An instance variable is a class member that is defined without using the static modifier.
The assigned value of a class variable is the same across all objects instantiated from a given class. An example of a class variable would be private static point equatorLatitude = 0. This value will be the same across each object you instantiate, as one would want to use a consistent value for each object. By contrast, the scope of an instance variable is the instance (or copy) of the object you are invoking. The instance variable is declared in the class, and may be given a default value like private point currLatitude = 0. However the current location referenced in one object may be San Francisco, USA, and you would want to override the default value to currLatitude = 37.7750, but another object may reference La Paz, Bolivia and you would instead want currLatitude = 16.4942. Each class variable and instance variable you invoke with the object lives in memory for the life of that object.
A simple definition is that instance variables are things an object knows about itself, but the class does not know about. 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. Changing the value of a class variable changes that value for all objects. Instance variables can be used by all methods of a class unless the method is declared as static. You access instance variables directly from their containing object instances.
In programming languages such as Java, instance variables are stored on the stack memory allocated by the Operating system. This contrasts with reference variables (variables that are references to existing instance variables) which are stored on the heap.
Famous quotes containing the word variable:
“There is not so variable a thing in nature as a ladys head-dress.”
—Joseph Addison (16721719)