Programming Search⌘K

Conceptcore

Objects and messages

Also called object, message, message passing, receiver, object identity, object state, boxing, everything is an object.

An object is a unit of a running program that holds state, offers behavior through messages or methods, and has an identity that tells it apart from objects with equal state.

Applies to
core-languages

Idea

An object is a unit of a running program that holds state, offers behavior and has an identity. The state is the data in its fields. The behavior is the set of operations that other code can ask it to do, which object-oriented languages call methods or messages. The identity tells one object from another even when their state is equal. Code does not change an object's state directly: it sends the object a message, and the object decides what to do. Python, JavaScript, Java, C#, C++ and Smalltalk are built around objects, and Go, Rust and C write the same pattern with structs, methods and tables of functions.

def make_counter(start=0):
    count = start  # state that only receive can reach

    def receive(message, *args):  # behavior: answer a message
        nonlocal count
        if message == "inc":
            count += args[0] if args else 1
            return count
        if message == "value":
            return count
        return f"does not understand: {message}"

    return receive


a = make_counter()
b = make_counter(10)
a("inc")
a("inc", 5)
print(a("value"), b("value"))
print(b("reset"))

c = a  # a second name for the same object
c("inc")
print(a("value"), a is c, a is b)  # identity: c and a are one object
Output
6 10
does not understand: reset
7 True False

The program makes objects from closures, with no class at all. Each call to make_counter makes a new object: a function that keeps a private count and answers the messages inc and value. Code outside cannot reach count except by sending a message, and a message that the object does not know gets a reply, not a crash. a and b have separate state. c = a makes no new object, so a message sent through c changes what a reports, and is shows that a and c are one object.

How it works

State, behavior and identity. The Python data model states the three parts: "Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory."1 The Rust book quotes the definition of the Design Patterns book: "Object-oriented programs are made up of objects. An object packages both data and the procedures that operate on that data."2 Identity matters when state can change: two accounts with the same balance are still two accounts, and a deposit to one must not reach the other. See value equality and identity.

Messages and receivers. Smalltalk took the view that all computing is objects sending messages. Dan Ingalls stated the principle in 1981: "Computing should be viewed as an intrinsic capability of objects that can be uniformly invoked by sending messages."3 The object that gets a message is the receiver, and it chooses the method that answers it, "with the understanding that the receiver knows best how to carry out the desired operation".3 In most languages, sending a message is a method call such as a.deposit(50), and the choice of method at run time is dynamic dispatch. Python and Smalltalk also let an object answer a message for which it has no method, through __getattr__ and doesNotUnderstand:.

References to objects. In Python, JavaScript, Java and C#, variables do not contain objects; they contain references to objects. The Java Language Specification states it: "An object is a class instance or an array. The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object."4 Assignment copies the reference, so two variables can reach one object, and a change through either one is visible through both. This sharing, called aliasing, is how a program builds graphs of objects, and it is also the source of many bugs. See pointers and references.

Objects as storage. C and C++ use the word object in a wider sense: any region of storage that holds a value, including a single int. cppreference lists the properties: "An object, in C++, has size (can be determined with sizeof); alignment requirement (can be determined with alignof); storage duration (automatic, static, dynamic, thread-local); lifetime (bounded by storage duration or temporary); type; value (which may be indeterminate, e.g. for default-initialized non-class types); optionally, a name."5 In this sense objects are values, and assignment copies the state into a second object. The two meanings meet in C++ classes, whose objects have storage and also behavior.

Objects without classes. A class is one way to make objects with the same shape, but not the only way. MDN defines a JavaScript object without classes: "An object is a collection of properties, and a property is an association between a name (or key) and a value."6 Object literals in JavaScript, anonymous types in C#, anonymous classes in Java, closures that hold private variables, and prototypes all make objects. Go and Rust put methods on any named type, and an interface value or trait object pairs the data with a table of the methods of its type. See classes and instances and prototype-based programming.

Everything an object, or not. In Smalltalk, Python and Ruby, every value is an object, including numbers, functions and classes, so every value answers messages. Java and JavaScript keep primitive values, such as int and JavaScript numbers, outside the world of objects for speed, and wrap them in objects when code treats them as objects; Java calls this boxing. C# unifies the types, so int derives from object, but it boxes a value type when code stores it as object. Ingalls gave the reason for the uniform design: "Uniform reference is achieved simply by associating a unique integer with every object in the system."3

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiom
C#Native
JavaScriptNative
TypeScriptNativeAs JavaScript, with object types and interfaces that the compiler checks.
GoIdiom
RustIdiom
KotlinNativeEvery value is an object in the language, object declarations create singletons and object expressions create anonymous objects; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLIdiomRows hold state and have keys for identity, and some databases add object types with methods.
BashDoes not applyBash values are strings and arrays of strings, with no methods.
PowerShellNativeEvery value in the pipeline is a .NET object with properties and methods; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLIdiomThe browser represents each element as a DOM object with properties and methods.
CSSDoes not applyRules hold no objects.
Regular expressionsDoes not applyA pattern holds no objects.
Language Verdict Mechanism
Python native every value is an object with an identity, a type and a value
JavaScript native objects are collections of properties; primitives are wrapped
TypeScript native as JavaScript, with object types checked by the compiler
Java native class instances and arrays; primitives are boxed
Kotlin native every value is an object in the language; object declarations
C# native every type derives from object; value types are boxed
Go idiom methods on any named type; interface values
Rust idiom structs and enums with impl; trait objects
C idiom structs with tables of function pointers
C++ native objects as typed storage; classes with virtual functions
Bash n/a values are strings and arrays of strings
PowerShell native every pipeline value is a .NET object
SQL idiom rows hold state and keys give identity
Regex n/a no objects
HTML idiom each element is a DOM object
CSS n/a no objects

The languages split on two questions. The first is whether every value is an object: Python and Kotlin say yes, C# says yes with boxing for value types, and Java and JavaScript keep primitives apart. The second is whether variables hold objects or references to them: Python, JavaScript and Java always use references, C++ and C hold objects in variables and use pointers to share them, and C#, Go and Rust let the type or the code choose.

Each example file shows how the language makes objects, how a message reaches its receiver, and what an assignment copies. The Python wrong block shows three rows of a grid that are one list object, and the JavaScript wrong block shows a property set on a string that disappears, because a string is not an object.

PythonGitHub
import math


class Logged:
    def __init__(self, target):
        self.target = target

    def __getattr__(self, name):  # called for a message with no method
        print("message:", name)
        return getattr(self.target, name)


for thing in (5, "hi", [1, 2], len, math, Logged):
    print(type(thing).__name__, isinstance(thing, object))

print((5).__add__(3), "hi".upper())  # operators are messages too
print(getattr([3, 1, 2], "index")(2))  # a message chosen at run time

log = Logged([3, 1, 2])
print(log.count(1))
Output
int True
str True
list True
builtin_function_or_method True
module True
type True
8 HI
2
message: count
1

This code runs but gives a wrong answer on purpose.

row = [0, 0, 0]
grid = [row] * 3  # three references to one list object
grid[0][0] = 1
print(grid)
print(grid[0] is grid[1])
Output
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
True
  • Verdict: native. Every value in Python is an object: numbers, strings, functions, modules and classes all have a type, an identity and attributes. Operators are method calls, so 5 + 3 sends the message __add__ to 5. getattr sends a message whose name is known only at run time. When an attribute lookup fails, Python calls __getattr__, which lets an object answer messages that it has no method for, as the Logged wrapper does.
  • Variables hold references, so assignment never copies an object. The wrong block builds a grid with [row] * 3, which repeats one reference three times. A change through grid[0] appears in every row, and is shows that the rows are one object. Build each row anew, as in [[0] * 3 for _ in range(3)].
#include <iostream>
#include <memory>
#include <string>

struct Point {
    int x, y;
};

struct Shape {
    virtual ~Shape() = default;
    virtual double area() const = 0;
};

struct Square : Shape {
    double side;
    explicit Square(double s) : side(s) {}
    double area() const override { return side * side; }
};

int counter() {
    static int calls = 0; // one object for the whole program
    return ++calls;
}

int main() {
    int n = 5;              // an object with automatic storage
    auto p = std::make_unique<Point>(Point{1, 2}); // an object with dynamic storage
    Point q = *p;           // a new object with the same value
    q.x = 9;
    std::cout << sizeof n << ' ' << alignof(double) << ' ' << p->x << ' ' << q.x << '\n';

    int& r = n; // a reference is a name for an object, not an object
    r = 6;
    std::cout << n << ' ' << (&r == &n) << '\n';

    counter();
    std::cout << counter() << '\n';

    std::unique_ptr<Shape> s = std::make_unique<Square>(3);
    std::cout << s->area() << ' ' << sizeof(Square) / sizeof(void*) << '\n';
}
Output
4 8 1 9
6 1
2
9 2
  • Verdict: native. In C++ an object is a region of storage with a type, a size, an alignment, a storage duration, a lifetime and a value. An int is an object as much as an instance of a class is. Objects have automatic storage in a block, static storage for the whole program, as calls does, or dynamic storage from new or make_unique.
  • Objects are values: Point q = *p creates a second object with the same value. A reference is another name for an existing object and is not an object itself. An object of a class with virtual functions holds a hidden pointer to the table of virtual functions, which is why a Square holding one double is two words wide on common platforms.
JavaGitHub
import java.util.ArrayList;

public class Main {
    interface Greeter {
        String greet(String name);
    }

    record Point(int x, int y) {}

    public static void main(String[] args) {
        Object[] things = {42, "hi", new int[] {1, 2}, new Point(1, 2), new ArrayList<String>()};
        for (Object t : things) {
            System.out.print(t.getClass().getSimpleName() + " ");
        }
        System.out.println();

        int n = 42; // a primitive value, not an object
        Object boxed = n; // boxing makes an Integer object
        System.out.println(boxed.getClass().getName() + " " + boxed.equals(42));

        Greeter polite = new Greeter() { // an object of an anonymous class
            public String greet(String name) {
                return "Good day, " + name;
            }
        };
        Greeter brief = name -> "Hi " + name;
        System.out.println(polite.greet("ana") + " / " + brief.greet("bo"));

        Point p = new Point(1, 2);
        Point q = p; // copies the reference, not the object
        System.out.println((p == q) + " " + (p == new Point(1, 2)));
    }
}
Output
Integer String int[] Point ArrayList 
java.lang.Integer true
Good day, ana / Hi bo
true false
  • Verdict: native. In Java an object is a class instance or an array, and variables of reference types hold references to objects. The eight primitive types, such as int and double, are not objects: they have no methods and no identity. Assigning a primitive to Object boxes it in a wrapper object such as Integer. Every object knows its class through getClass.
  • An anonymous class creates one object of a class that has no name, and a lambda creates an object of a functional interface. == on references compares identity, so p == q is true after q = p, and a new Point with the same values is a different object.
#include <stdio.h>

struct counter;

struct counter_ops {
    void (*inc)(struct counter *self, int by);
    int (*value)(const struct counter *self);
};

struct counter {
    const struct counter_ops *ops; /* behavior, shared by all counters */
    int n;                         /* state, one copy per counter */
};

static void inc(struct counter *self, int by) { self->n += by; }
static int value(const struct counter *self) { return self->n; }

static const struct counter_ops counter_ops = {inc, value};

int main(void) {
    struct counter a = {&counter_ops, 0};
    struct counter b = {&counter_ops, 10};
    a.ops->inc(&a, 5); /* send the message inc to a */
    printf("%d %d\n", a.ops->value(&a), b.ops->value(&b));

    struct counter *p = &a; /* a second way to reach a */
    p->ops->inc(p, 1);
    printf("%d %d\n", a.n, p == &a);

    int x = 7; /* in C, x is also an object: a region of storage */
    printf("%zu %d\n", sizeof x, x);
    return 0;
}
Output
5 10
6 1
4 7
  • Verdict: idiom. The C standard calls any region of storage that holds a value an object, so x is an object with no behavior. Objects in the sense of this page are written by hand: a struct holds the state, and a pointer to a shared table of function pointers holds the behavior. A call through a.ops->inc(&a, 5) sends a message and passes the receiver explicitly. The Linux kernel, GTK and many C libraries use this pattern.
using System;

object[] things = { 42, "hi", new[] { 1, 2 }, 3.5m, new Point(1, 2) };
foreach (var t in things)
{
    Console.Write(t.GetType().Name + " ");
}
Console.WriteLine();

int n = 1;
object box = n; // boxing copies the value into a new object
n = 2;
Console.WriteLine($"{n} {box} {box is int}");

var ana = new { Name = "ana", Age = 30 }; // an anonymous type
Console.WriteLine($"{ana} {ana.GetType().Name.StartsWith("<>")}");

var a = new Counter();
var b = a; // a second reference to the same object
b.Inc();
Console.WriteLine($"{a.Count} {ReferenceEquals(a, b)}");

record Point(int X, int Y);

class Counter
{
    public int Count { get; private set; }

    public void Inc() => Count++;
}
Output
Int32 String Int32[] Decimal Point 
2 1 True
{ Name = ana, Age = 30 } True
1 True
  • Verdict: native. Every C# type derives from object, value types included, so a list of object can hold an int, a string, an array and a record, and each knows its type through GetType. Assigning a value type to object boxes it: the runtime copies the value into a new object on the heap, so the box keeps 1 after n changes to 2.
  • An anonymous type creates an object with read-only properties and a class name that the compiler generates. Variables of class types hold references, so b and a reach one Counter, and ReferenceEquals confirms it.
JavaScriptGitHub
const account = {
  owner: "ana",
  balance: 100,
  deposit(amount) {
    this.balance += amount;
    return this;
  },
};
account.deposit(50).deposit(25);
console.log(account.owner, account.balance);

account.close = function () {
  return `${this.owner} closed`;
};
console.log(account.close(), Object.keys(account).join(","));

const message = "deposit";
account[message](5); // a message chosen at run time
console.log(account.balance);

const logged = new Proxy(account, {
  get(target, name) {
    if (!(name in target)) return () => `does not understand: ${String(name)}`;
    return target[name];
  },
});
console.log(logged.withdraw());

console.log(typeof 5, typeof account, (5).toFixed(1));
Output
ana 175
ana closed owner,balance,deposit,close
180
does not understand: withdraw
number object 5.0

This code runs but gives a wrong answer on purpose.

let label = "total";
label.unit = "EUR"; // sets a property on a temporary wrapper object
console.log(label.unit);
const boxed = new String("total");
boxed.unit = "EUR";
console.log(boxed.unit);
Output
undefined
EUR
  • Verdict: native. A JavaScript object is a collection of properties, and an object literal creates one directly, with no class. A method is a property whose value is a function, and this names the object through which it was called. A program can add properties at any time, and account[message] sends a message whose name is in a variable. A Proxy can catch every property access, including names that the object lacks.
  • Numbers, strings and booleans are primitives, not objects. When code reads a property of a primitive, JavaScript wraps it in a temporary object, which is why (5).toFixed(1) works.
  • The wrong block sets a property on a string. The assignment goes to a temporary wrapper that is thrown away at once, so the next read finds nothing. In sloppy code the assignment fails with no error, and in strict mode and modules it throws a TypeError. Store extra data in an object, not on a primitive.
package main

import "fmt"

type Celsius float64

func (c Celsius) String() string { return fmt.Sprintf("%.1f C", float64(c)) }

type Counter struct{ n int }

func (c *Counter) Inc() { c.n++ }

func newGreeter(greeting string) func(string) string {
	return func(name string) string { return greeting + ", " + name } // state in a closure
}

func main() {
	things := []any{42, "hi", []int{1, 2}, Celsius(21.5), &Counter{}}
	for _, t := range things {
		fmt.Printf("%T ", t)
	}
	fmt.Println()

	var s fmt.Stringer = Celsius(21.5) // any type with String answers this message
	fmt.Println(s.String())

	a := &Counter{}
	b := a // a second pointer to the same struct
	b.Inc()
	c := *a // a copy of the struct value
	c.Inc()
	fmt.Println(a.n, c.n, a == b)

	hi := newGreeter("Hi")
	fmt.Println(hi("ana"))
}
Output
int string []int main.Celsius *main.Counter 
21.5 C
1 2 true
Hi, ana
  • Verdict: idiom. Go does not use the word object, but any named type can have methods, even a type based on float64 such as Celsius. A value of any type can go in an interface value, which holds the value and its dynamic type, and %T prints that type. An interface such as fmt.Stringer names a message, and every type with a matching method answers it.
  • Struct values copy on assignment, so c := *a makes a separate counter, while pointers share one. A closure that holds its own variables is a small object with one method, as newGreeter shows.
RustGitHub
use std::fmt::Display;
use std::rc::Rc;

trait Shape {
    fn area(&self) -> f64;
}

struct Square(f64);
struct Circle(f64);

impl Shape for Square {
    fn area(&self) -> f64 {
        self.0 * self.0
    }
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        3.0 * self.0 * self.0
    }
}

fn show(items: &[&dyn Display]) {
    for item in items {
        print!("{item} ");
    }
    println!();
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0)), Box::new(Circle(1.0))];
    for s in &shapes {
        print!("{} ", s.area()); // each object answers with its own method
    }
    println!();

    show(&[&42, &"hi", &2.5]);
    println!(
        "{}",
        std::mem::size_of::<&dyn Shape>() / std::mem::size_of::<usize>()
    );

    let a = Rc::new(String::from("shared"));
    let b = Rc::clone(&a); // a second owner of the same object
    println!("{} {}", Rc::ptr_eq(&a, &b), Rc::strong_count(&a));
}
Output
4 3 
42 hi 2.5 
2
true 2
  • Verdict: idiom. Rust has no objects in the sense of Smalltalk or Java: structs and enums hold data, and impl blocks give them methods. A trait object, such as Box<dyn Shape> or &dyn Display, is the closest form: a pointer to the data plus a pointer to a table of the methods of its type, which is why &dyn Shape is two words wide. Each object in the vector answers area with the method of its own type.
  • Values have one owner and move by default, so sharing one object needs a reference or a shared pointer such as Rc. Rc::ptr_eq compares identity, and the count shows two owners.
  • Actors. An actor is an object that runs on its own and gets its messages through a mailbox, one at a time. Erlang processes and Akka actors work in this way. See the actor model.
  • Value objects. Some objects have no meaningful identity, such as dates, money amounts and points. They are immutable and compare by value. See immutability.
  • Entities. Other objects are defined by their identity, such as a customer or an order, whose state changes over time while the object stays the same.
  • Proxies and wrappers. An object can stand in for another and forward its messages, as Proxy in JavaScript and __getattr__ in Python allow. See decorator pattern.
  • Closures as objects. A closure that holds private variables is an object with one method, and a closure that dispatches on a message name is an object with many. See closures.
  • Object graphs. Objects that hold references to other objects form a graph, which a program must copy, compare, serialize or free as a whole. See reference counting.
  • Encapsulation. An object hides its state behind its messages, so that it can keep its invariants. See encapsulation.

Pitfalls

  • Aliasing by accident. Two variables that hold the same reference change one object. The wrong block in the Python file shows a grid whose rows are one list. Copy an object when two parts of a program need separate state.
  • Identity where value is meant. Comparing objects with == in Java, or is in Python, tests whether they are the same object, not whether their values are equal. Use equals in Java and == in Python to compare values.
  • Primitives treated as objects. A property set on a JavaScript string disappears, as the wrong block in the JavaScript file shows, and a boxed Integer in Java can be null. Know which values are objects in the language.
  • Objects that are only data. An object whose fields every caller reads and writes directly has state but no behavior that protects it. Move the operations that change the state into the object.
  • Too many small objects. Each object costs a header and an allocation in most managed languages. A hot loop that makes millions of short-lived objects can spend more time on allocation and collection than on its work. Use arrays of values, or reuse objects, where profiling shows the cost.
  • Unknown messages that fail late. In dynamic languages, a message that an object cannot answer fails only when the program runs. Tests, type hints and static checkers find these errors earlier.

Cost

An object costs the memory of its fields plus a header in most managed runtimes: 8 to 16 bytes in common JVM configurations, 16 bytes on 64-bit .NET, and more in CPython, where every value, even a small integer, is a heap object with a reference count and a pointer to its type. C, C++, Go and Rust objects without virtual functions have no header, so a struct of two int fields takes 8 bytes. Objects reached through references add one memory load for each access and scatter data across the heap, which costs cache misses; arrays of values keep data close together. A message send costs a direct call when the compiler knows the receiver's type, and a lookup or an indirect call otherwise.

History

Ole-Johan Dahl and Kristen Nygaard introduced objects in Simula 67, where each object of a class held its own data and procedures and modelled one part of a simulated system. Alan Kay coined the term object-oriented programming around 1967, as a graduate student at the University of Utah. At Xerox PARC, Kay, Dan Ingalls, Adele Goldberg and others built Smalltalk in the 1970s, in which every value is an object and all computing is message sending.3 Carl Hewitt's actor model of 1973 took the idea of objects that communicate only by messages into concurrent computing.

In the 1980s, C++ and Objective-C added objects to C, and in the 1990s, Python, Java and JavaScript made objects the main way to structure programs. Java kept primitive types outside its objects for speed, and Java 5 added automatic boxing in 2004. C# unified its types under object in 2002. Go in 2009 and Rust in 2015 kept methods and interfaces but dropped classes and inheritance, which separated the idea of an object from the idea of a class.

References

  1. Data model, The Python Language Reference, 3.1 Objects, values and types
  2. Characteristics of Object-Oriented Languages, The Rust Programming Language, Objects Contain Data and Behavior
  3. Design Principles Behind Smalltalk, Daniel H. H. Ingalls, BYTE Magazine, August 1981, Storage Management; Messages
  4. Chapter 4, Types, Values, and Variables, The Java Language Specification, Java SE 25 Edition, 4.3.1 Objects
  5. Object, cppreference.com, Introduction
  6. Working with objects, JavaScript Guide, MDN Web Docs, Introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/3R8PW0/text.yaml