Object

On this page 7

An object is a runtime entity in object-oriented programming that combines state and behavior: it holds data in fields and exposes operations, called methods, that read or change that data. Every object has an identity that distinguishes it from all other objects, even from one whose field values are identical.

In most mainstream languages, an object is created as an instance of a class, which acts as its blueprint. Programs are then built as networks of objects that send messages to one another by calling methods, so the object is the basic unit of design, reuse and reasoning in this paradigm.

What an object is made of

A classic definition describes an object through three properties: state, behavior and identity. State is the current set of field values, behavior is the set of methods the object responds to, and identity is what makes it a distinct thing in memory. Two objects can be equal in state and still be different objects.

The following table summarizes these properties and how they typically appear in code.

PropertyMeaningTypical representation
StateData the object currently holdsFields, attributes, instance variables
BehaviorOperations the object can performMethods bound to the object
IdentityDistinctness from every other objectMemory reference or object ID
The three core properties of an object

Internally, a typical object in a managed runtime such as the JVM or the .NET CLR consists of an object header and the field data. The header usually stores a pointer to the class or type information, which enables dynamic dispatch, plus bookkeeping for garbage collection, hashing and locking. On 64-bit JVMs the header commonly occupies 12 to 16 bytes, which is why millions of tiny objects carry a noticeable memory overhead.

Object lifecycle in object-oriented programming

Every object passes through a lifecycle of creation, use and destruction. Creation allocates memory and runs a constructor that establishes valid initial state; use consists of method calls; destruction releases memory and any resources the object owns.

StageWhat happensLanguage mechanisms
AllocationMemory is reserved for fields and headernew operator, factory functions
InitializationConstructor sets a valid initial stateConstructors, initializers
UseMethods read and modify stateMethod calls, message sends
UnreachabilityNo references to the object remainScope exit, reassignment
DestructionMemory and resources are releasedGarbage collection, destructors, reference counting
Stages of the object lifecycle

The release strategy differs sharply between languages. C++ uses deterministic destruction, so a destructor runs exactly when an object leaves scope, which supports the RAII idiom for files and locks. Java, C# and Python rely mainly on garbage collection or reference counting, so memory is reclaimed eventually, and external resources should be closed explicitly with constructs such as try-with-resources or context managers.

How an object relates to class, interface and other concepts

An object is often confused with the class that defines it. The class is a description that exists at compile time or as metadata; the object is a concrete instance at runtime with its own memory. One class can produce millions of objects, and the four pillars of the paradigm describe how these objects are structured and connected.

ConceptRelationship to an objectExample
ClassBlueprint from which objects are instantiatedInvoice defines fields and methods
InterfaceContract that an object promises to fulfillAn object implements Comparable
EncapsulationHides the object’s state behind methodsPrivate balance field with a deposit method
InheritanceLets an object’s class reuse a parent classSavingsAccount extends Account
PolymorphismLets different objects answer the same messageEach shape object computes its own area
Object compared with neighboring concepts

Not every object system uses classes. Prototype-based languages such as JavaScript create objects that delegate directly to other objects, and object literals can be built without any class at all. In languages such as Python and Ruby, everything is an object, including numbers, functions and the classes themselves.

Identity, equality and copying

Distinguishing identity from equality is one of the most practical skills in object-oriented code. Identity asks whether two references point to the same object; equality asks whether two objects represent the same value. Java uses == for identity and equals() for equality, while Python uses is and ==.

The kind of object determines which comparison makes sense, as the following table shows.

Kind of objectDefined byComparisonExample
Entity objectIdentity that persists over timeBy identifierCustomer, order
Value objectIts field values onlyBy value, usually immutableMoney amount, date range
Service objectBehavior, little or no stateRarely comparedPayment gateway client
Data transfer objectPlain fields for moving dataBy value when neededAPI request payload
Kinds of objects and how they are compared

Copying follows the same logic. A shallow copy duplicates the outer object but shares the objects it references, while a deep copy duplicates the whole graph. Choosing the wrong one leads to unintended shared state, where changing one copy silently changes another.

Design guidelines and common pitfalls

Well-designed objects are small, cohesive and responsible for their own invariants. A constructor should leave the object in a valid state, and every public method should keep it valid, so that no caller can observe a half-built or inconsistent object.

  • Anemic objects: classes with only getters and setters push all logic elsewhere and lose the benefit of encapsulation.
  • God objects: one object that knows and does too much becomes hard to test and change.
  • Leaking internal state: returning a reference to a mutable internal list lets callers bypass the object’s rules.
  • Broken equality contracts: overriding equality without a matching hash function breaks hash-based collections.
  • Excessive allocation: creating many short-lived objects in hot loops increases garbage collection pressure.

A useful rule of thumb is tell, do not ask: instead of reading an object’s fields and making decisions outside it, ask the object to perform the operation. This keeps behavior next to the data it depends on and reduces coupling between objects.

In everyday language

An object is a small, self-contained piece of a program that knows some facts and can do some things. A bank account object knows its balance and can accept a deposit or refuse a withdrawal that is too large.

The class is like the printed form for opening an account, and each object is one filled-in, real account. Two accounts can show the same balance and still be two different accounts, just as two people can have the same name. Programs work by having these objects ask each other to do things.

Seen in the real world

An online store models its checkout with objects. Each shopping cart object holds a list of line-item objects and offers methods such as addItem, removeItem and total. Prices are represented as immutable money value objects that combine an amount and a currency, so adding euros to dollars raises an error instead of producing a wrong number.

When 5,000 customers shop at the same time, the server holds 5,000 separate cart objects created from the same class, each with its own state. Because the cart enforces its own rules, such as a maximum quantity of 10 per item, no other part of the code can create an invalid order. Bugs stay local and easy to find, and the team can add a discount feature by changing a single class.