Conceptcore
Object-oriented programming
Also called OOP, object orientation, objects and classes, classes, inheritance, encapsulation, dynamic dispatch, virtual methods, vtable, prototype-based programming.
Object-oriented programming builds a program from objects that keep private state and answer method calls, so code can ask an object to act without knowing its exact kind.
- Applies to
- core-languages
Idea
Object-oriented programming organizes a program as a set of objects. An object keeps some state and offers operations, called methods, that read or change that state. Other code asks an object to do something by calling a method, and the object decides how to respond. Two objects of different kinds can answer the same request in different ways, so the calling code does not need to know which kind it has:
class Account:
def __init__(self, owner):
self.owner = owner
self._balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self._balance += amount
def month_end(self):
pass
def report(self):
return f"{self.owner}: {self._balance}"
class Savings(Account):
def month_end(self):
self._balance += self._balance // 100
accounts = [Account("ana"), Savings("bo")]
for a in accounts:
a.deposit(500)
a.month_end()
print(a.report())
ana: 500
bo: 505
The loop calls month_end on each account and does not ask which class the account has. The Savings class inherits deposit and report from Account and replaces month_end. The balance is only changed through methods, so the rule that a deposit is positive is in one place.
How it works
Objects package state with behavior. The book Design Patterns by Gamma, Helm, Johnson and Vlissides defines the idea in this way: "Object-oriented programs are made up of objects. An object packages both data and the procedures that operate on that data."1 Most languages describe the shape of an object with a class. The Python tutorial states that "Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made."2
Dynamic dispatch selects the method. A call such as shape.area() names an operation, not a function. The language finds the method from the object at run time. The Java specification states that for an instance method, "the actual method to be invoked will be determined at run time, using dynamic method lookup".3 Compiled languages usually implement this with a table of function pointers for each class, called a virtual method table or vtable, and each object holds a pointer to the table of its class. A call loads the table pointer, loads the method from a fixed slot, and calls it. C programs build the same structure by hand. An LWN article on the Linux kernel describes "a pure vtable being a structure which contains only function pointers where the first argument of each is a pointer to some other structure (the object type) which itself contains a pointer to this vtable".4 Dynamic languages such as Python and Smalltalk look up the method by name in the class and its ancestors, often with a cache.
Encapsulation hides the state. If only the methods of an object can change its state, the object can keep its invariants, and its representation can change without changes to the code that uses it. The C# guide describes encapsulation as "Hiding the internal state and functionality of an object and only allowing access through a public set of functions."5 Languages enforce this to different degrees. Java, C# and C++ check private at compile time, JavaScript enforces # fields at run time, and Python relies on a naming convention.
Inheritance shares code and defines subtypes. A class can extend another class. It then gets the fields and methods of the parent and can override some of them. The Rust book describes inheritance as a mechanism by which an object can "inherit elements from another object's definition, thus gaining the parent object's data and behavior without you having to define them again".1 Inheritance does two jobs at once: it reuses an implementation, and it makes the child a subtype that can be used where the parent is expected. Many later designs separate the two jobs. Interfaces, protocols and traits give the subtype relation without shared state, and composition gives reuse without the subtype relation.
Classes or prototypes. In a class-based language, objects are instances of classes, and the class holds the methods. In a prototype-based language such as Self or JavaScript, an object inherits directly from another object. MDN explains that when a property is not on an object, the lookup continues on its prototype, then on the prototype of the prototype, until it "is found or the end of the prototype chain is reached".6 The JavaScript class keyword is a convenient form for this model, and MDN notes that "classes do not bring a new inheritance pattern."6
Two views of the same name. Alan Kay, who led the Smalltalk work at Xerox PARC, put the emphasis on messages and not on classes: "OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things."7 He thought of objects "being like biological cells and/or individual computers on a network, only able to communicate with messages".7 The tradition of Simula, C++ and Java puts the emphasis on classes as types, with static checks and inheritance. Both views agree on objects with private state and on dynamic dispatch. They differ in how late the binding is and in how much the type system knows. The Rust book notes that "There is no consensus in the programming community about what features a language must have to be considered object oriented."1
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Classes are final and methods are closed unless marked open, interfaces can have default methods, and data classes and sealed classes model data; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | SQL works on relations, not objects; some databases add user-defined types with methods, but queries do not use dynamic dispatch. |
| Bash | Absent | |
| PowerShell | Native | The class keyword defines classes with properties, methods, inheritance and interfaces, and every value in the pipeline is a .NET object; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | HTML elements become objects in the DOM, but the markup itself has no classes or methods. |
| CSS | Does not apply | A CSS class is a selector for elements and is not related to classes in programming languages. |
| Regular expressions | Does not apply | A regular expression describes text and has no objects. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | classes, multiple inheritance, super() with a method resolution order, duck typing; privacy by convention |
| JavaScript | native | prototype chains, class syntax, #private fields |
| TypeScript | native | JavaScript classes plus interfaces, abstract classes and access modifiers checked at compile time |
| Java | native | classes, single inheritance, interfaces with default methods, virtual by default, sealed and record |
| Kotlin | native | classes final by default, open and override, interfaces, data and sealed classes |
| C# | native | classes, single inheritance, interfaces, virtual, abstract, override and new |
| Go | native | methods on any named type, implicit interfaces, struct embedding; no classes or inheritance |
| Rust | native | structs with methods, traits, trait objects with dyn; no inheritance of data |
| C | idiom | structs of function pointers as hand-built vtables |
| C++ | native | classes, multiple inheritance, opt-in virtual, override and final |
| Bash | absent | no objects; naming conventions only |
| PowerShell | native | class with inheritance and interfaces; all values are .NET objects |
| SQL | n/a | relations, not objects |
| Regex, HTML, CSS | n/a | no objects or methods |
Python and JavaScript are dynamic. A method is found by name when the call runs, so any object with a method of the right name can take part. This is duck typing. Python allows more than one base class and resolves the order of lookup with the C3 linearization, which is visible in __mro__. The Python tutorial warns that a mutable value in a class attribute, such as a list, is shared by all instances.2
Java and C# are class-based and statically typed. Each class has one parent class and any number of interfaces. In Java, instance methods can be overridden unless they are final. In C#, a method must be marked virtual or abstract before a derived class can override it, and a method marked new hides the base method, so the static type of the variable decides which method runs.5 Java's sealed interfaces and record classes, and the equivalent features in C#, move these languages toward the algebraic data types of functional languages.
C++ makes dynamic dispatch opt-in. Only a virtual function keeps the overriding behavior when a derived object is used through a pointer or a reference to the base class.8 A class with no virtual functions needs no vtable, and its calls cost the same as calls to plain functions. C++ also allows multiple inheritance of classes with state, which brings the problem of a shared base class, solved with virtual inheritance.
Go and Rust have no inheritance. The Go FAQ answers the question of whether Go is object-oriented with "Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy."9 A Go type satisfies an interface when it has the methods, with no declaration. Rust uses traits, and the Rust book explains that it takes "the different approach of using trait objects instead of inheritance to achieve polymorphism at runtime."1 Both languages use composition for reuse.
C has no objects, but large C programs use the object-oriented pattern by hand. The Linux kernel has many structures of function pointers, such as file_operations, that act as vtables.4
class Shape:
def __init__(self, name):
self.name = name
def area(self):
raise NotImplementedError
def describe(self):
return f"{self.name} with area {self.area():.2f}"
class Circle(Shape):
def __init__(self, r):
super().__init__("circle")
self.r = r
def area(self):
return 3.14159 * self.r * self.r
class Square(Shape):
def __init__(self, side):
super().__init__("square")
self.side = side
def area(self):
return self.side * self.side
class Label:
def describe(self):
return "a label, not a shape"
for thing in [Circle(1), Square(2), Label()]:
print(thing.describe())
print(Circle.__mro__)
circle with area 3.14
square with area 4.00
a label, not a shape
(<class '__main__.Circle'>, <class '__main__.Shape'>, <class 'object'>)
This code runs but gives a wrong answer on purpose.
class Dog:
tricks = []
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick)
a = Dog("Fido")
b = Dog("Buddy")
a.add_trick("roll over")
b.add_trick("play dead")
print(a.tricks)
['roll over', 'play dead']
- Verdict: native. Every value in Python is an object, and a class is an object too. A class can have more than one base class, and
super()follows the method resolution order in__mro__. - The loop calls
describeon aLabelthat has no relation toShape. Python looks up methods by name when the call runs, so any object with the right method works. This is duck typing. - Privacy is a convention. A name that starts with an underscore is internal, but the language does not stop other code from using it.
- In the wrong block,
tricksis an attribute of the class, so all dogs share one list. Create the list in__init__withself.tricks = [].
#include <iostream>
#include <memory>
#include <vector>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
virtual const char* name() const { return "shape"; }
};
class Circle : public Shape {
double r_;
public:
explicit Circle(double r) : r_(r) {}
double area() const override { return 3.14159 * r_ * r_; }
const char* name() const override { return "circle"; }
};
class Square final : public Shape {
double side_;
public:
explicit Square(double side) : side_(side) {}
double area() const override { return side_ * side_; }
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(1.0));
shapes.push_back(std::make_unique<Square>(2.0));
for (const auto& s : shapes) {
std::cout << s->name() << " " << s->area() << "\n";
}
}
circle 3.14159
shape 4
This code runs but gives a wrong answer on purpose.
#include <iostream>
struct Animal {
virtual ~Animal() = default;
virtual const char* speak() const { return "..."; }
};
struct Dog : Animal {
const char* speak() const override { return "woof"; }
};
void by_value(Animal a) { std::cout << a.speak() << "\n"; }
void by_ref(const Animal& a) { std::cout << a.speak() << "\n"; }
int main() {
Dog d;
by_value(d);
by_ref(d);
}
...
woof
- Verdict: native. C++ has classes, multiple inheritance, access control and
virtualfunctions. Functions are not virtual by default, so a call costs no more than a plain call unless the class asks for dynamic dispatch. overrideasks the compiler to check that a base function with the same signature exists.finalstops further derivation. A base class that is deleted through a pointer needs a virtual destructor.- In the wrong block,
by_valuecopies only theAnimalpart of theDog. This is object slicing, and the copy has theAnimalbehavior. Pass polymorphic objects by reference or pointer.
import java.util.List;
public class Main {
sealed interface Shape permits Circle, Square {
double area();
default String describe() {
return getClass().getSimpleName() + " " + String.format("%.2f", area());
}
}
record Circle(double r) implements Shape {
public double area() {
return Math.PI * r * r;
}
}
record Square(double side) implements Shape {
public double area() {
return side * side;
}
@Override
public String describe() {
return "a square of side " + side;
}
}
public static void main(String[] args) {
List<Shape> shapes = List.of(new Circle(1), new Square(2));
for (Shape s : shapes) {
System.out.println(s.describe());
}
System.out.println(new Square(2).equals(new Square(2)));
}
}
Circle 3.14
a square of side 2.0
true
- Verdict: native. All code in Java is in classes, and instance methods are virtual by default. The method that runs is chosen at run time from the class of the object.
- A class extends one class and implements any number of interfaces. Interfaces can have
defaultmethods. - A
sealedinterface lists all its implementations, and arecordis a class for immutable data withequals,hashCodeandtoStringalready written.
#include <stdio.h>
struct shape;
struct shape_ops {
double (*area)(const struct shape *s);
const char *name;
};
struct shape {
const struct shape_ops *ops;
};
struct circle {
struct shape base;
double r;
};
struct square {
struct shape base;
double side;
};
static double circle_area(const struct shape *s)
{
const struct circle *c = (const struct circle *)s;
return 3.14159 * c->r * c->r;
}
static double square_area(const struct shape *s)
{
const struct square *q = (const struct square *)s;
return q->side * q->side;
}
static const struct shape_ops circle_ops = { circle_area, "circle" };
static const struct shape_ops square_ops = { square_area, "square" };
int main(void)
{
struct circle c = { { &circle_ops }, 1.0 };
struct square q = { { &square_ops }, 2.0 };
struct shape *all[] = { &c.base, &q.base };
for (int i = 0; i < 2; i++)
printf("%s %.2f\n", all[i]->ops->name, all[i]->ops->area(all[i]));
return 0;
}
circle 3.14
square 4.00
- Verdict: idiom. C has no classes or methods, but the pattern is common. A table of function pointers acts as a vtable, and each object starts with a pointer to its table.
- Because
baseis the first member, a pointer to astruct circlecan be converted to a pointer to itsstruct shapeand back. The Linux kernel uses this pattern for files, devices and file systems.
var animals = new List<Animal> { new Dog("Rex"), new Cat("Tom") };
foreach (var a in animals)
{
Console.WriteLine(a.Describe());
}
Animal hidden = new Quiet("Bo");
Console.WriteLine(hidden.Speak());
Console.WriteLine(((Quiet)hidden).Speak());
abstract class Animal(string name)
{
public string Name { get; } = name;
public abstract string Speak();
public string Describe() => $"{Name} says {Speak()}";
}
class Dog(string name) : Animal(name)
{
public override string Speak() => "woof";
}
class Cat(string name) : Animal(name)
{
public override string Speak() => "meow";
}
class Quiet(string name) : Dog(name)
{
public new string Speak() => "...";
}
Rex says woof
Tom says meow
woof
...
- Verdict: native. A C# class extends one class and implements any number of interfaces. Methods are not virtual by default: the base class marks a method
virtualorabstract, and the derived class must writeoverride. - A method marked
newhides the base method instead of overriding it. The call then depends on the static type of the variable, which is whyhidden.Speak()printswoof.
class Counter {
#count = 0;
increment() {
this.#count += 1;
return this;
}
get value() {
return this.#count;
}
}
class StepCounter extends Counter {
constructor(step) {
super();
this.step = step;
}
increment() {
for (let i = 0; i < this.step; i++) super.increment();
return this;
}
}
const c = new StepCounter(5).increment().increment();
console.log(c.value);
console.log(Object.getPrototypeOf(c) === StepCounter.prototype);
console.log(Object.getPrototypeOf(StepCounter.prototype) === Counter.prototype);
console.log(typeof StepCounter);
const plain = { greet() { return "hello from " + this.name; } };
const obj = Object.create(plain);
obj.name = "obj";
console.log(obj.greet(), Object.hasOwn(obj, "greet"));
10
true
true
function
hello from obj false
- Verdict: native. JavaScript objects inherit from other objects through a prototype chain. When a property is not on the object, the engine looks at its prototype, then at the prototype of the prototype, and so on.
- The
classsyntax builds the same chain. A class is a function, and its methods live on the object in itsprototypeproperty. Fields that start with#are private, and the engine rejects access from outside the class body. Object.createmakes an object with a given prototype and no class at all.
interface HasArea {
area(): number;
}
abstract class Shape implements HasArea {
protected readonly name: string;
constructor(name: string) {
this.name = name;
}
abstract area(): number;
describe(): string {
return `${this.name} with area ${this.area().toFixed(2)}`;
}
}
class Rect extends Shape {
private w: number;
private h: number;
constructor(w: number, h: number) {
super("rect");
this.w = w;
this.h = h;
}
area(): number {
return this.w * this.h;
}
}
const unit: HasArea = { area: () => 1 };
const all: HasArea[] = [new Rect(2, 3), unit];
console.log(all.map((s) => s.area()));
console.log(new Rect(1.5, 2).describe());
[ 6, 1 ]
rect with area 3.00
- Verdict: native. TypeScript adds interfaces, abstract classes and the access modifiers
private,protectedandpublicto the class syntax of JavaScript. - Interfaces are structural. The plain object
unithas no class, but it has anareamethod, so it is aHasArea. - The checks run at compile time only. At run time,
privatefields are ordinary properties. Use#fields for privacy that the engine enforces.
package main
import "fmt"
type Shape interface {
Area() float64
}
type Named struct {
Name string
}
func (n Named) Describe() string { return "I am " + n.Name }
type Rect struct {
Named
W, H float64
}
func (r Rect) Area() float64 { return r.W * r.H }
type Celsius float64
func (c Celsius) Area() float64 { return 0 }
func main() {
r := Rect{Named{"rect"}, 2, 3}
fmt.Println(r.Describe(), r.Name)
shapes := []Shape{r, Celsius(21)}
for _, s := range shapes {
fmt.Printf("%T %.1f\n", s, s.Area())
}
}
I am rect rect
main.Rect 6.0
main.Celsius 0.0
- Verdict: native. Go has methods on any named type and interfaces, but no classes and no type hierarchy. The Go FAQ answers the question "Is Go an object-oriented language?" with "Yes and no".
- A type satisfies an interface when it has the methods. It does not declare the interface by name.
- Embedding
NamedinRectpromotes the fields and methods ofNamed, sor.Describe()works. This is composition: the method still receives theNamedvalue, not theRect, so there is no virtual dispatch back to the outer type.
trait Shape {
fn area(&self) -> f64;
fn describe(&self) -> String {
format!("shape with area {:.2}", self.area())
}
}
struct Circle {
r: f64,
}
struct Square {
side: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.r * self.r
}
}
impl Shape for Square {
fn area(&self) -> f64 {
self.side * self.side
}
fn describe(&self) -> String {
format!("square of side {}", self.side)
}
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle { r: 1.0 }), Box::new(Square { side: 2.0 })];
for s in &shapes {
println!("{}", s.describe());
}
let total: f64 = shapes.iter().map(|s| s.area()).sum();
println!("{total:.2}");
}
shape with area 3.14
square of side 2
7.14
- Verdict: native. Rust has structs with methods, privacy at the module level, and traits with default methods. It has no inheritance of data between structs.
- A
Box<dyn Shape>is a trait object: a pointer to the value and a pointer to a table of the methods ofShapefor its type. Calls through it use dynamic dispatch. Generic functions with aT: Shapebound use static dispatch instead.
circle_area() { echo $(( 3 * $1 * $1 )); }
square_area() { echo $(( $1 * $1 )); }
a_kind=circle a_size=1
b_kind=square b_size=2
for obj in a b; do
k=${obj}_kind s=${obj}_size
echo "${!k} $("${!k}_area" "${!s}")"
done
circle 3
square 4
- Verdict: absent. Bash has no objects, classes or methods. A script can keep the fields of an object in variables with a common prefix and pick a function from a name, as above, but this is a convention with no help from the shell.
Variations and related ideas
- Interfaces and traits. These define a set of methods without state. They give subtyping without inheritance of an implementation. See interfaces and subtyping.
- Composition over inheritance. An object holds other objects and forwards calls to them. This is the advice of the Design Patterns book, and the basis of the decorator and strategy patterns.
- Mixins and multiple inheritance. A class can take methods from several sources. Python, C++ and Scala allow this. Languages with single inheritance often add default methods in interfaces to get some of the same effect.
- Multiple dispatch. CLOS, Julia and Dylan choose a method from the types of all arguments, not only the first. Single dispatch languages use the visitor pattern to get double dispatch.
- The actor model. Kay's description of objects as small computers that exchange messages is close to the actor model, in which each actor has a mailbox and runs on its own. Erlang processes are a working example.
- Closures as objects. A closure is a function with captured state, and an object is state with functions. Each can model the other. See closures.
- Expression problem. In object-oriented code it is easy to add a new kind of object and hard to add a new operation to all kinds. In code that uses sum types and pattern matching, the opposite is true.
Pitfalls
- Deep hierarchies. Each level of inheritance adds behavior that a reader must find in another file. A change to a base class can break subclasses that depend on its internal call order. This is called the fragile base class problem. The Rust book adds that "Inheritance is often at risk of sharing more code than necessary."1
- Subclasses that are not subtypes. A subclass must keep the promises of its parent. A
Squarethat extends a mutableRectanglebreaks code that sets the width and the height on their own. This is the Liskov substitution principle. - Object slicing in C++. A derived object copied into a variable of the base type loses its derived part, and the copy calls base methods. Pass polymorphic objects by reference or by pointer.
- Missing virtual destructor. In C++, deleting a derived object through a pointer to a base class without a virtual destructor is undefined behavior.8
- Calls to overridable methods from a constructor. The derived part of the object is not ready yet. Java and C# call the derived override on the half-built object, and C++ calls the base version. Neither result is what most authors expect.
- Shared mutable class attributes. In Python, a list defined in the class body is one list for all instances.2
- Getters and setters for every field. A class that exposes all its fields through accessors has no real encapsulation. Methods should express what the object does, not mirror its fields.
Cost
A virtual call loads a table pointer from the object, loads a function pointer from the table, and makes an indirect call. This is a few cycles more than a direct call when the branch predictor guesses well. The larger cost is that the compiler cannot inline a call when it does not know the target, which blocks other optimizations. Compilers remove this cost when they can prove the type, for example with final classes or with whole-program analysis, and JIT compilers inline the common target and add a guard. Each object with virtual methods holds one extra pointer. Objects reached through pointers are often spread over the heap, which costs cache misses when a program processes many of them. Data-oriented designs store the fields of many objects in arrays for this reason.
History
Ole-Johan Dahl and Kristen Nygaard designed Simula at the Norwegian Computing Center in the 1960s to write simulations. Simula 67 introduced classes, objects, subclasses and virtual procedures. Alan Kay studied Simula and Ivan Sutherland's Sketchpad, and in the 1970s led the group at Xerox PARC that built Smalltalk, in which everything is an object and computation is done by sending messages. Kay wrote that "Simula-I had neither classes as objects nor inheritance".10 He also wrote that he did not like the way Simula did inheritance, so he "decided to leave out inheritance as a built-in feature until I understood it better."7 Bjarne Stroustrup added Simula's classes to C in C with Classes, which became C++ in the 1980s. Objective-C added Smalltalk's messages to C. Java and C# made class-based object-oriented programming the mainstream style of the 1990s and 2000s. Later languages such as Go and Rust kept objects and interfaces and left out inheritance.
References
- The Rust Programming Language, Characteristics of Object-Oriented Languages, Rust 1.99.1, Objects Contain Data and Behavior; Inheritance as a Type System and as Code Sharing
- The Python Tutorial, 9. Classes, Python 3.14 documentation, 9. Classes; 9.3.5 Class and Instance Variables
- The Java Language Specification, Java SE 25 Edition, 8.4.9 Overloading
- Object-oriented design patterns in the kernel, part 1, Neil Brown, LWN.net, 2011, Method Dispatch
- Object-Oriented programming (C#), Microsoft Learn, introduction; Polymorphism
- Inheritance and the prototype chain, MDN Web Docs, Inheritance with the prototype chain
- Dr. Alan Kay on the Meaning of Object-Oriented Programming, email to Stefan Ram, 2003, full email
- virtual function specifier, cppreference.com, Explanation; Virtual destructor
- Frequently Asked Questions (FAQ), The Go Programming Language, Is Go an object-oriented language?
- The Early History of Smalltalk, Alan C. Kay, ACM SIGPLAN Notices 28(3), 1993, I. 1960-66, Early OOP and other formative ideas of the sixties
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag XAZRJ8 Edit this page History Report an error Markdown