Instance variable

Also known as: member variable

On this page 7

An instance variable is a variable declared in a class whose value belongs to each individual object created from that class. In object-oriented programming, every instance receives its own copy, so changing the value in one object never affects another. Instance variables are also called member variables or fields, and together they form the state of an object.

Instance variables contrast with class variables, which are shared by all instances, and with local variables, which exist only while a method runs. Choosing the right kind of variable, and protecting it with suitable access rules, is one of the basic design decisions in Programming with classes.

How instance variables store object state

When a program creates an object, the runtime allocates memory for every instance variable declared in the class and its superclasses. In Java or C++, the compiler knows the layout in advance, and each field lives at a fixed offset inside the object. In Python and Ruby, instance variables are usually stored in a per-object dictionary or similar table, which allows attributes to be added at run time.

Methods reach instance variables through a reference to the current object, named this in Java, C++ and C#, self in Python and Swift, and written with an @ prefix in Ruby. Because each method call receives the object it operates on, the same method code can read and modify different state for different objects.

The lifetime of an instance variable matches the lifetime of its object. It is created during construction, typically initialized by a constructor, and released when the object is destroyed or reclaimed by the garbage collector.

Instance, class and local variables compared

The three kinds of variables differ in ownership, lifetime and visibility. Confusing them is a frequent source of defects, especially when a value intended for one object is accidentally shared by all of them. The table summarizes the differences.

KindOwned byLifetimeTypical declaration
Instance variableEach objectAs long as the object existsField without static, or assigned to self
Class variableThe class itselfAs long as the class is loadedstatic field, or class-level attribute
Local variableOne method callUntil the call returnsDeclared inside a method body
ParameterOne method callUntil the call returnsListed in the method signature
Variable kinds in object-oriented code

A common trap in Python is defining a mutable default at class level, such as a list, and expecting each object to have its own. All instances then share one list until code assigns a new list to self. The correct approach is to create mutable values inside the constructor.

Declaring and initializing instance variables across languages

Languages differ in how strictly instance variables must be declared. Statically typed languages require a declaration with a type in the class body, while dynamic languages often create the variable on first assignment. The following table shows the conventions in widely used languages.

LanguageDeclaration styleAccess inside methodsDefault value
JavaTyped field in class bodythis.name or nameZero, false or null
C++Typed data memberthis->name or nameIndeterminate for primitive types
C#Typed field or auto-propertythis.name or nameType default
PythonAssigned to self in methodsself.nameNone until assigned
RubyAssigned with @ prefix@namenil until assigned
JavaScriptClass field or this assignmentthis.nameundefined until assigned
Instance variable syntax in common languages

Because default values differ, a safe habit is to initialize every instance variable explicitly in the constructor or in the declaration. In C++, reading an uninitialized primitive member is undefined behavior, which can produce unpredictable results in production.

Encapsulation and access control

Instance variables are usually hidden behind access modifiers so that only the class can change them directly. This supports encapsulation: the class guarantees its own invariants, such as a balance that never becomes negative, and outside code interacts through methods, getters and setters, or properties.

Access levelVisible toTypical use
PrivateThe declaring class onlyDefault choice for internal state
ProtectedThe class and its subclassesState that subclasses must extend
Package or internalCode in the same package or assemblyCooperation between closely related classes
PublicAny codeSimple data carriers and immutable records
Access levels for instance variables

Python and JavaScript rely partly on naming conventions: a leading underscore signals that an attribute is internal. JavaScript also supports true private fields with a # prefix, and Python applies name mangling to attributes that start with two underscores. Marking instance variables final, readonly or const when they never change after construction makes objects easier to reason about and safer to share between threads.

Design guidance and common mistakes

Well-designed classes keep the number of instance variables small and make each one necessary for the object’s responsibility. A class with dozens of fields often hides several concepts that should be separate objects, which is where composition over inheritance helps. Values that can be computed from other fields usually should not be stored, because redundant state can become inconsistent.

  • Shadowing: a parameter or local variable with the same name hides the instance variable, so an assignment silently changes the wrong one.
  • Leaking mutable references: returning an internal list lets callers modify object state without passing through validation.
  • Shared state across threads: unsynchronized writes to instance variables cause race conditions when one object is used concurrently.
  • Overuse of public fields: exposing fields directly makes later changes to representation a breaking change.

Subclasses inherit the instance variables of their parents, even private ones that they cannot access directly. Changing a superclass layout can therefore affect memory use and serialization formats of every subclass, which is worth considering before adding fields to widely used base classes.

In simple terms

Think of a class as a blank form, such as a membership card template with spaces for a name and a number. Each card printed from that template is an object, and each card has its own name and its own number written on it. Those personal fields are instance variables.

If one member changes their name, no other card changes. That is the whole idea: each object remembers its own information, while the template only describes what information every card should hold.

A practical example

A developer builds an inventory system for a warehouse with about 12,000 products. A Product class declares instance variables for the stock-keeping code, the name, the unit price and the quantity on hand. Each of the 12,000 objects keeps its own quantity, so recording a sale of five units of one item changes only that object.

An early version stored the list of supplier contacts as a class-level list by mistake, and adding a supplier to one product added it to every product. Moving the list into the constructor as a private instance variable, exposed only through an add method that checks for duplicates, fixed the shared-data defect and made each product’s supplier list independent and validated.