Conceptcore
Classes and instances
Also called class, instance, object type, class member, instance variable, class variable, static member, metaclass, struct with methods.
A class describes the fields and methods of a kind of object. An instance is one object made from it, with its own field values, sharing the methods and the class data.
- Applies to
- core-languages
Idea
A class describes a kind of object: the fields that each object of the kind holds, and the methods that work on them. An instance is one object made from the class, with its own values for the fields. The class exists once, and every instance links to it, so all instances share one copy of the methods and of any data that belongs to the class itself. A class is also a type: code can state that a variable holds an Account, and the compiler or the runtime checks it. Python, JavaScript, Java, C#, Kotlin, C++ and PowerShell have classes. Go and Rust put methods on structs and other types without classes, and C writes the pattern by hand with structs and functions.
def deposit(self, amount):
self["balance"] += amount
def interest(self):
return self["balance"] * self["class"]["rate"]
# A class: a name, data shared by all instances, and a table of methods.
Account = {"name": "Account", "rate": 0.02,
"methods": {"deposit": deposit, "interest": interest}}
def new(cls, **fields): # an instance: its own fields and a link to its class
return {"class": cls, **fields}
def send(obj, name, *args): # a method call: find the method in the class
return obj["class"]["methods"][name](obj, *args)
a = new(Account, owner="ana", balance=100)
b = new(Account, owner="bo", balance=500)
send(a, "deposit", 50)
print(a["balance"], b["balance"]) # each instance has its own fields
print(send(a, "interest"), send(b, "interest"))
Account["rate"] = 0.05 # one change in the class reaches every instance
print(send(a, "interest"), send(b, "interest"))
print(a["class"] is b["class"]) # the methods exist once, in the class
150 500
3.0 10.0
7.5 25.0
True
The program builds a class with plain dictionaries. Account holds a shared value, rate, and a table of methods. new makes an instance: a dictionary with its own fields and a link to its class. send calls a method by looking up its name in the class of the object and passing the object as the first argument. Each instance keeps its own balance, but a change to rate in the class reaches both instances, because they read it through their link. Every language with classes does this work, with faster lookups and with checks at compile time.
How it works
A class bundles data and behavior. The Python tutorial gives the definition: "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."1 MDN describes JavaScript classes in the same terms: "Classes are a template for creating objects. They encapsulate data with code to work on that data."2 The Java Language Specification lists the parts: "The body of a class declares members (fields, methods, classes, and interfaces), instance and static initializers, and constructors".3 Access modifiers such as private decide which code can touch each member. See encapsulation and constructors.
Instance members and class members. An instance field has one value in each object, and a class field, called static in Java, C#, C++ and JavaScript, has one value for the whole class. The Python tutorial states the rule: "Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class".1 A static method belongs to the class and has no instance, so it can reach only the static fields, unless it receives an instance as an argument. Factory methods, counters and constants are the usual static members.
Methods receive the instance. A method is a function with one hidden parameter, the instance on which it is called. Python and Rust make the parameter visible as self, and Go names it in the receiver. Java, C#, C++ and JavaScript call it this and pass it without a declaration. A call such as a.deposit(50) does two things: it finds the method through the class of a, and it passes a as the receiver. In languages that look up methods at run time, the first step is dynamic dispatch, which lets a subclass replace a method. See class inheritance.
Reference types and value types. In Python, JavaScript and Java, a variable of a class type holds a reference, and assigning it copies the reference, so two variables can name one object. In C++, "A class is a user-defined type",4 and its objects are values: assignment copies the fields, and a program shares an object through a pointer or a reference. C# and Swift offer both kinds. The C# design guidelines state the choice: "One of the basic design decisions every framework designer faces is whether to design a type as a class (a reference type) or as a struct (a value type)."5 Value types avoid a heap allocation and copy on assignment, which suits small values such as points and money. See value equality and identity.
Classes at run time. In Python, JavaScript, Smalltalk and Ruby, a class is an object that a program can pass around, inspect and change, and a program can create new classes while it runs. Java and C# keep a run-time object for each class, which reflection uses to list fields and call methods, but the set of members is fixed when the class is compiled. In C++, a class exists only at compile time, apart from the table of virtual functions and the type information for typeid and dynamic_cast.
Methods without classes. Go and Rust separate the data from the methods. A struct declares the fields, and methods are declared elsewhere, for the type. The Go FAQ answers the question whether Go is object-oriented: "Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy."6 Methods in Go can belong to any named type, even an integer type, and shared behavior comes from interfaces. Rust adds methods in impl blocks and shared behavior through traits. See interfaces and composition over inheritance.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | As JavaScript, with access modifiers, abstract classes and types for fields checked by the compiler. |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Native | Classes with primary constructors and properties, data classes and companion objects in place of static members; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Idiom | A table definition describes the fields of its rows, and some databases add user-defined types with methods. |
| Bash | Does not apply | Bash has no classes; associative arrays hold data but not methods. |
| PowerShell | Native | A class keyword defines .NET classes with properties, methods, static members and constructors; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Idiom | A custom element is defined by a JavaScript class, and the class attribute names CSS classes, which is a different idea. |
| CSS | Does not apply | A CSS class is a label for selectors, not a type. |
| Regular expressions | Does not apply | A pattern has no types; a character class is a different idea. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | class; class objects of type type; self |
| JavaScript | native | class over prototypes; static and #private fields |
| TypeScript | native | as JavaScript, with access modifiers and typed fields |
| Java | native | classes, static members, records |
| Kotlin | native | classes, data classes, companion objects |
| C# | native | classes, structs, records |
| Go | idiom | struct types with methods; no classes |
| Rust | idiom | struct and impl; traits; no classes |
| C | idiom | struct and functions that take a pointer |
| C++ | native | class and struct, static and const members |
| Bash | n/a | no classes |
| PowerShell | native | class keyword for .NET classes |
| SQL | idiom | table definitions; user-defined types in some databases |
| Regex | n/a | no types; character classes are a different idea |
| HTML | idiom | custom elements defined by classes |
| CSS | n/a | CSS classes are labels for selectors |
The languages with classes differ in three ways. The first is whether objects are references or values: Python, JavaScript, Java and Kotlin use references for every class, C++ uses values, and C# lets each type choose. The second is how much of a class exists at run time: Python and JavaScript classes are ordinary objects that a program can change, while Java and C# classes are fixed after compilation. The third is how static data is held: Kotlin replaces static members with a companion object, Python and JavaScript store them on the class object, and Go and C use variables at package or file level.
Each example file defines an account with an owner, a balance, a deposit method and data that all accounts share, and makes two instances. The wrong blocks show a mistake that comes from the model of each language: a mutable class attribute that all Python instances share, a JavaScript method that loses its this, a C# struct that a list returns as a copy, a Go method that changes a copy of its receiver, and a C++ object that loses its derived part when it is copied into its base class.
class Account:
rate = 0.02 # class attributes: one value, shared by all instances
opened = 0
def __init__(self, owner, balance=0):
self.owner = owner # instance attributes: one set per object
self.balance = balance
Account.opened += 1
def deposit(self, amount): # a method: a function stored in the class
self.balance += amount
return self
def interest(self):
return round(self.balance * self.rate, 2)
def __repr__(self):
return f"Account({self.owner!r}, {self.balance})"
a = Account("ana", 100)
b = Account("bo")
a.deposit(50)
print(a, b, Account.opened)
print(a.interest())
print(Account.deposit(b, 10)) # a.deposit(10) means Account.deposit(a, 10)
print(type(a) is Account, type(Account)) # a class is an object too
Savings = type("Savings", (Account,), {"rate": 0.05}) # a class made at run time
print(Savings("cy", 100).interest(), Account.opened)
Account('ana', 150) Account('bo', 0) 2
3.0
Account('bo', 10)
True <class 'type'>
5.0 3
This code runs but gives a wrong answer on purpose.
class Cart:
items = [] # a class attribute: one list, stored in the class
def add(self, item):
self.items.append(item) # finds the class's list and changes it
a = Cart()
b = Cart()
a.add("tea")
print(b.items, a.items is b.items)
['tea'] True
- Verdict: native. A
classstatement creates a class object that holds the methods and the class attributes. Each instance has its own dictionary of attributes, which__init__usually fills. A lookup such asa.ratesearches the instance first and then the class, so instances share class attributes until one assigns its own.a.deposit(10)is a short form ofAccount.deposit(a, 10), which is why each method takesselfas its first parameter. A class is itself an object, of typetype, and a program can create a new class at run time by callingtype. - The wrong block puts a list in a class attribute. Every instance finds the same list through the class, so an item added through
aappears inb. Create mutable state in__init__, so that each instance gets its own.
#include <iostream>
#include <string>
#include <utility>
class Account {
public:
static constexpr double rate = 0.02; // static: one value for the class
Account(std::string owner, long balance) : owner_(std::move(owner)), balance_(balance) { ++opened_; }
void deposit(long amount) { balance_ += amount; }
double interest() const { return balance_ * rate; } // const: does not change the object
static int opened() { return opened_; }
friend std::ostream& operator<<(std::ostream& os, const Account& a)
{
return os << "Account(" << a.owner_ << ", " << a.balance_ << ")";
}
private: // members of a class are private unless declared otherwise
std::string owner_;
long balance_;
static inline int opened_ = 0;
};
struct Point { // members of a struct are public by default
int x, y;
};
int main()
{
Account a{"ana", 100};
Account b{"bo", 0};
a.deposit(50);
std::cout << a << ' ' << b << ' ' << Account::opened() << '\n';
std::cout << a.interest() << '\n';
Point p{1, 2};
Point q = p; // objects are values: q is a copy
q.x = 9;
std::cout << p.x << ' ' << q.x << '\n';
}
Account(ana, 150) Account(bo, 0) 2
3
1 9
This code runs but gives a wrong answer on purpose.
#include <iostream>
#include <string>
struct Shape {
virtual ~Shape() = default;
virtual std::string name() const { return "shape"; }
};
struct Circle : Shape {
double r = 1;
std::string name() const override { return "circle"; }
};
void print(Shape s) { std::cout << s.name() << '\n'; } // takes a Shape by value
int main()
{
Circle c;
print(c); // copies only the Shape part of c: the object is sliced
const Shape& ref = c;
std::cout << ref.name() << '\n';
}
shape
circle
- Verdict: native.
classandstructdeclare the same kind of type and differ only in the default access: members of aclassare private and members of astructare public. Static members belong to the class, and aconstmember function promises not to change the object. Objects are values: assigning one copies its members, asq = pshows, and a pointer or reference is needed to share one object. - The wrong block passes a
Circleto a function that takes aShapeby value. The copy keeps only theShapepart of the object, so the call reachesShape::name. This is called slicing. Pass objects of a class hierarchy by reference or by pointer, as the second call does.
import java.util.Objects;
final class Account {
static final double RATE = 0.02; // static: one value for the class
private static int opened = 0;
private final String owner; // instance fields: one set per object
private long balance;
Account(String owner, long balance) {
this.owner = Objects.requireNonNull(owner);
this.balance = balance;
opened++;
}
Account deposit(long amount) {
balance += amount;
return this;
}
double interest() { return balance * RATE; }
static int opened() { return opened; } // a static method has no this
@Override public String toString() { return "Account(" + owner + ", " + balance + ")"; }
}
// A record: a class whose fields, constructor, accessors, equals and toString come from one line.
record Point(int x, int y) {}
public class Main {
public static void main(String[] args) {
var a = new Account("ana", 100);
var b = new Account("bo", 0);
a.deposit(50);
System.out.println(a + " " + b + " " + Account.opened());
System.out.println(a.interest());
System.out.println(a.getClass().getSimpleName() + " " + (a.getClass() == Account.class));
System.out.println(new Point(1, 2) + " " + new Point(1, 2).equals(new Point(1, 2)));
}
}
Account(ana, 150) Account(bo, 0) 2
3.0
Account true
Point[x=1, y=2] true
- Verdict: native. Every method and field in Java belongs to a class. Instance fields belong to each object and static fields to the class, and a static method has no
this. Fields are usuallyprivateand reached through methods, andfinalfields cannot change after construction. Each object knows its class at run time, throughgetClass, andAccount.classis the sameClassobject. A record declares a class for plain data in one line, with the constructor, accessors,equals,hashCodeandtoStringgenerated from its components.
#include <stdio.h>
/* The data: a struct. */
struct account {
const char *owner;
long balance;
};
/* A file-level variable plays the role of a static field. */
static int opened = 0;
/* The behavior: functions that take a pointer to the struct, like this. */
static void account_init(struct account *a, const char *owner, long balance)
{
a->owner = owner;
a->balance = balance;
opened++;
}
static void account_deposit(struct account *a, long amount) { a->balance += amount; }
static double account_interest(const struct account *a) { return a->balance * 0.02; }
int main(void)
{
struct account a, b;
account_init(&a, "ana", 100);
account_init(&b, "bo", 0);
account_deposit(&a, 50);
printf("%s %ld, %s %ld, %d\n", a.owner, a.balance, b.owner, b.balance, opened);
printf("%.1f\n", account_interest(&a));
return 0;
}
ana 150, bo 0, 2
3.0
- Verdict: idiom. C has no classes. A
structholds the data, and functions whose names start with the name of the type take a pointer to it as their first parameter, which plays the role ofthis. Aconstpointer marks a function that only reads. Astaticvariable at file level is shared by all values of the type and hidden from other files. To hide the fields too, a header declares the struct without its members, and only the implementation file defines them.
var a = new Account("ana", 100);
var b = a; // a class is a reference type: b and a are the same object
b.Deposit(50);
Console.WriteLine($"{a.Balance} {ReferenceEquals(a, b)} {Account.Opened}");
var p = new Point(1, 2);
var q = p; // a struct is a value type: q is a copy
q.X = 9;
Console.WriteLine($"{p.X} {q.X}");
var r1 = new Money(5, "EUR");
var r2 = new Money(5, "EUR");
Console.WriteLine($"{r1} {r1 == r2}"); // records compare by value
class Account(string owner, decimal balance)
{
public static int Opened { get; private set; }
public string Owner { get; } = owner;
public decimal Balance { get; private set; } = Count(balance);
private static decimal Count(decimal b)
{
Opened++;
return b;
}
public void Deposit(decimal amount) => Balance += amount;
}
struct Point(int x, int y)
{
public int X = x;
public int Y = y;
}
record Money(decimal Amount, string Currency);
150 True 1
1 9
Money { Amount = 5, Currency = EUR } True
This code runs but gives a wrong answer on purpose.
var points = new List<Point> { new(1, 2) };
var p = points[0]; // the indexer returns a copy of the struct
p.Move(10);
Console.WriteLine($"{points[0].X} {p.X}");
struct Point(int x, int y)
{
public int X = x;
public int Y = y;
public void Move(int dx) => X += dx; // a mutable struct: changes only this copy
}
1 11
- Verdict: native. C# has two kinds of types with fields and methods. A
classis a reference type: assigning an instance copies the reference, sobandaname one object. Astructis a value type: assigning it copies the fields, so a change toqleavespalone. Arecordis a class whose equality compares the values of its properties. A primary constructor in the type header gives parameters that the members can use, and static members belong to the type. - The wrong block changes a struct that it read from a list. The indexer returns a copy, so
Movechanges the copy and the list keeps the old value. Avoid mutable structs, or write the changed copy back withpoints[0] = p.
"use strict";
class Account {
static rate = 0.02; // static fields: one value, stored on the class
static opened = 0;
#pin; // a private instance field
constructor(owner, balance = 0, pin = "0000") {
this.owner = owner; // public instance fields, one set per object
this.balance = balance;
this.#pin = pin;
Account.opened++;
}
deposit(amount) {
this.balance += amount;
return this;
}
interest() { return this.balance * Account.rate; }
checkPin(pin) { return pin === this.#pin; }
}
const a = new Account("ana", 100, "1234");
const b = new Account("bo");
a.deposit(50);
console.log(a.balance, b.balance, Account.opened);
console.log(a.interest(), a.checkPin("1234"));
console.log(typeof Account, Object.getPrototypeOf(a) === Account.prototype);
console.log(a.deposit === b.deposit); // methods live once, on the prototype
150 0 2
3 true
function true
true
This code runs but gives a wrong answer on purpose.
"use strict";
class Counter {
count = 0;
increment() { this.count++; }
}
const c = new Counter();
const inc = c.increment; // the method, without its object
try {
inc(); // this is undefined inside the call
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
const bound = c.increment.bind(c);
bound();
console.log(c.count);
TypeError: Cannot read properties of undefined (reading 'count')
1
- Verdict: native. A
classdeclaration creates a constructor function, and its methods go on the function'sprototypeobject, so all instances share one copy of each method. Fields declared in the class body belong to each instance,staticfields belong to the class, and fields whose names start with#are private: code outside the class body cannot read them.typeof Accountis"function", because a class is a function with special rules for calls. - The wrong block reads a method from an object and calls it alone. The value of
thisdepends on the form of the call, not on where the method came from, so the callinc()has no object, andthisisundefined. Bind the method withbind, or wrap the call in an arrow function, before passing it as a callback.
package main
import "fmt"
// Account is a struct type; its methods are declared outside the type.
type Account struct {
Owner string
balance int // lower case: visible only inside the package
}
var opened int // package-level state plays the role of a static field
func NewAccount(owner string, balance int) *Account {
opened++
return &Account{Owner: owner, balance: balance}
}
// A pointer receiver: the method can change the account.
func (a *Account) Deposit(amount int) { a.balance += amount }
// A value receiver: the method gets a copy.
func (a Account) String() string { return fmt.Sprintf("Account(%s, %d)", a.Owner, a.balance) }
// Methods can belong to any named type, not only to structs.
type Celsius float64
func (c Celsius) Fahrenheit() float64 { return float64(c)*9/5 + 32 }
func main() {
a := NewAccount("ana", 100)
b := NewAccount("bo", 0)
a.Deposit(50)
fmt.Println(a, b, opened)
fmt.Println(Celsius(100).Fahrenheit())
fmt.Printf("%T\n", a)
}
Account(ana, 150) Account(bo, 0) 2
212
*main.Account
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
type Account struct{ balance int }
// A value receiver: Deposit changes a copy of the account.
func (a Account) Deposit(amount int) { a.balance += amount }
func main() {
a := Account{balance: 100}
a.Deposit(50)
fmt.Println(a.balance)
}
100
- Verdict: idiom. Go has no classes. A named type, usually a struct, holds the data, and methods are declared separately with a receiver. A method can belong to any named type in the same package, such as
Celsius, which is afloat64. Names that start with a capital letter are exported from the package, and the others are private to it, so the package is the unit of encapsulation, not the type. A package-level variable plays the role of a static field, and a function namedNewAccountplays the role of a constructor. - The wrong block declares
Depositwith a value receiver. The method gets a copy of the account and changes the copy, so the balance stays 100. Use a pointer receiver,func (a *Account), for methods that change the receiver, and use the same kind of receiver for all methods of a type.
use std::fmt;
// The data: a struct with private fields.
pub struct Account {
owner: String,
balance: i64,
}
// The behavior: an impl block, separate from the data.
impl Account {
pub const RATE: f64 = 0.02; // an associated constant, one for the type
pub fn new(owner: &str, balance: i64) -> Self {
Account {
owner: owner.to_string(),
balance,
}
}
pub fn deposit(&mut self, amount: i64) {
self.balance += amount; // &mut self: the method changes the account
}
pub fn interest(&self) -> f64 {
self.balance as f64 * Self::RATE // &self: the method only reads
}
}
impl fmt::Display for Account {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Account({}, {})", self.owner, self.balance)
}
}
fn main() {
let mut a = Account::new("ana", 100);
let b = Account::new("bo", 0);
a.deposit(50);
println!("{} {}", a, b);
println!("{}", a.interest());
Account::deposit(&mut a, 10); // the same call, written as a function
println!("{}", a);
}
Account(ana, 150) Account(bo, 0)
3
Account(ana, 160)
This code does not compile, on purpose. The error is E0596.
struct Account {
balance: i64,
}
impl Account {
fn deposit(&mut self, amount: i64) {
self.balance += amount;
}
}
fn main() {
let a = Account { balance: 100 }; // not declared mut
a.deposit(50);
println!("{}", a.balance);
}
- Verdict: idiom. Rust has no classes. A
structholds the data and one or moreimplblocks add methods and associated constants. The first parameter of a method states what the method may do:&selfreads,&mut selfchanges, andselftakes ownership.a.deposit(50)is short forAccount::deposit(&mut a, 50). Traits, implemented in their ownimplblocks, give shared behavior such asDisplay. Fields are private to the module unless markedpub. - The failing block calls a method that takes
&mut selfon a variable that is not declaredmut, and the compiler reports error E0596. Declare the variable withlet mut.
Variations and related ideas
- Records and data classes. Java records, C# records, Kotlin data classes and Python dataclasses generate the constructor, equality and string form from a list of fields, for classes that are mainly data. See immutability.
- Prototypes. JavaScript classes are syntax over prototypes, and in Self and early JavaScript, objects inherit directly from other objects without classes. See prototype-based programming.
- Metaclasses. In Smalltalk and Python, a class is an instance of a metaclass, which controls how the class is created and how it behaves. Python's
typeis the default metaclass. - Open classes. Ruby, Smalltalk, Python and JavaScript let a program add methods to an existing class at run time. C# extension methods and Kotlin extension functions give a similar syntax without changing the class.
- Abstract and sealed classes. An abstract class cannot have instances and leaves some methods to its subclasses; a sealed or final class cannot have subclasses, or only those that it lists.
- Nested and inner classes. Java, C# and C++ let a class contain other classes. A Java inner class holds a reference to an instance of the outer class.
- Singletons and objects without classes. Kotlin and Scala
objectdeclarations create one instance with no separate class name, and JavaScript object literals create objects directly. - Classes in object-oriented design. A class is the main unit of design in most object-oriented languages. See object-oriented programming.
Pitfalls
- Shared mutable class data. A list or map stored in a class attribute or a static field is shared by every instance and every thread. The wrong block in the Python file shows a cart whose items appear in every cart.
- Lost receiver. A method read from an object and called later can lose its object. The wrong block in the JavaScript file shows
thisasundefined. - Copies of values. Changing a copy of a struct, or a method with a value receiver, changes nothing that the caller sees. The wrong blocks in the C# and Go files show both.
- Slicing. Copying a derived object into a variable of its base class type in C++ drops the derived part and its overrides. The wrong block in the C++ file shows this.
- Classes that do too much. A class with many unrelated fields and methods is hard to change and test. Split it by responsibility, and prefer small classes that hold other objects.
- Static state. Static fields act as global variables: they make tests depend on each other and can race between threads. Pass the state in, or hold it in an object that the program creates.
- Getters and setters for every field. Public accessors for all fields expose the representation as much as public fields do. Offer operations that keep the invariants of the class, such as
deposit, rather thansetBalance.
Cost
An instance costs the memory of its fields plus a header. In Java, C# and JavaScript, the header holds a pointer to the class or its hidden layout, and in C++ an object of a class with virtual functions holds a pointer to the table of virtual functions; a C++ class without them, a C struct, a Go struct and a Rust struct have no header. Python instances store their attributes in a dictionary, which costs more memory per object, unless the class declares __slots__. A method call costs a direct call when the compiler knows the class, which it can then inline, and an indirect call or a cached lookup when it does not. Instances of reference types need a heap allocation, which value types avoid.
History
Ole-Johan Dahl and Kristen Nygaard introduced classes and objects in Simula 67, for simulation programs in which each object of a class had its own data and its own procedures. Alan Kay and his group at Xerox PARC built Smalltalk in the 1970s, in which everything is an object and every object is an instance of a class, including the classes themselves. Bjarne Stroustrup added classes to C in C with Classes from 1979, which became C++, and Brad Cox and Tom Love created Objective-C in the early 1980s.
Python had classes from its first release in 1991, and Java 1.0, released in 1996, required every method to belong to a class. C# added structs as value types beside its classes in 2002. JavaScript added the class syntax over its prototypes in ECMAScript 2015 and private fields in ECMAScript 2022.2 Go in 2009 and Rust in 2015 left classes out and put methods on types directly.6 C# added records in 2020 and Java in 2021, which made classes for plain data short to write.
References
- Classes, The Python Tutorial, 9. Classes; 9.3.5 Class and Instance Variables
- Classes, MDN Web Docs, Introduction
- Chapter 8, Classes, The Java Language Specification, Java SE 25 Edition, Chapter 8, introduction
- Classes, cppreference.com, Introduction
- Choosing Between Class and Struct, .NET Framework design guidelines, Introduction
- Frequently Asked Questions (FAQ), The Go Programming Language, Is Go an object-oriented language?
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 BNR9SD Edit this page History Report an error Markdown