Conceptcore
Static members
Also called static member, static field, static method, class variable, class method, class attribute, static property, companion object, associated function, associated constant.
A static member belongs to a class, not to its instances: one shared variable, or a function that is called on the class and has no receiver object.
- Applies to
- core-languages
Idea
Most members of a class belong to each instance: each order has its own id and its own amount. A static member belongs to the class itself. A static field is one variable that all instances share, and a static method is a function that is called on the class and has no instance to work on. The Java tutorial says: "Fields that have the static modifier in their declaration are called static fields or class variables",1 and "Every instance of the class shares a class variable, which is in one fixed location in memory."
The usual uses are a counter of the instances, a constant such as a tax rate, a cache that all instances use, and functions that make instances, such as Order.fromText("50"). In Python:
class Order:
created = 0 # a class variable: one value for the class, shared by all orders
TAX_RATE = 0.2 # a constant, by the upper-case naming convention
def __init__(self, amount):
Order.created += 1 # change it through the class
self.id = Order.created # an instance variable: one value per order
self.amount = amount
@classmethod
def from_text(cls, text): # gets the class, so a subclass gets its own type
return cls(int(text))
@staticmethod
def is_valid(amount): # gets neither the class nor an instance
return amount > 0
def total(self):
return self.amount * (1 + Order.TAX_RATE)
class RushOrder(Order):
pass
a = Order(100)
b = RushOrder.from_text("50")
print(a.id, b.id, Order.created, type(b).__name__)
print(Order.is_valid(-5), a.total())
print(a.created, "created" in vars(a)) # read through the instance, stored on the class
1 2 2 RushOrder
False 120.0
2 False
created and TAX_RATE are on the class, so every order sees the same values. id and amount are on each order. from_text is a class method: it gets the class as cls, so RushOrder.from_text makes a RushOrder. is_valid is a static method: it gets neither the class nor an order.
How it works
- Storage. A static field has one place in memory for the whole program, or for each class when a language keeps one per subclass. C# says: "Only one copy of a static member exists, regardless of how many instances of the class are created."2 An instance field has one place in each object.
- No receiver. A static method gets no object, so it cannot read instance fields unless it gets an object as a parameter. Java says: "class methods cannot use the this keyword as there is no instance for this to refer to."1 C++ says: "Static member functions are not associated with any object."3 A call such as
Order.fromText("50")compiles to a plain function call with the class name as a namespace. - Class methods with a class receiver. Python and Smalltalk have a third kind. "A class method receives the class as an implicit first argument, just like an instance method receives the instance."4 It is not the same as a Java static method: "Class methods are different than C++ or Java static methods." In Smalltalk, a class is itself an object: "Each class is an instance of the metaclass of that class",5 and class methods are the methods of that metaclass.
- Initialization. A static field gets its value once, before its first use. Java and C# run the initializers of a class when the class is first used; C++ initializes static data members before
main, or on first use for a function-localstatic. Use a singleton depends on these rules. - Access. Most languages reach a static member through the class name:
Order.created,Order::created. Java and C++ also allowa.createdthrough an instance, C# does not, and in JavaScript "Static properties cannot be directly accessed on instances of the class."6
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | A static variable at file scope is shared by all calls and hidden from other files, and functions named with a prefix, such as order_create, play the part of class methods. |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | As JavaScript, and static members can also be private, protected or readonly, which the compiler checks; no example file because it would repeat the JavaScript one. |
| Go | Idiom | |
| Rust | Native | |
| Kotlin | Native | No static keyword; a companion object holds the class-level functions and properties, and an object declaration holds one shared instance; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | A table has no class-level members; a shared value is a row in another table or a sequence. |
| Bash | Does not apply | Bash has global variables and functions but no types that own them. |
| PowerShell | Native | Static properties and methods in class definitions, called as [Order]::Create(); no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | HTML has no types or members; static members of DOM classes belong to JavaScript. |
| CSS | Does not apply | CSS has no types or members. |
| Regular expressions | Does not apply | A pattern has no types or members. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | class attributes; @classmethod with cls; @staticmethod |
| JavaScript | native | static fields and methods on the class object; this is the class in a static method |
| TypeScript | native | as JavaScript, with private, protected and readonly static members |
| Java | native | static fields, methods, nested classes and initializer blocks |
| Kotlin | native | companion object members; object declarations; no static keyword |
| C# | native | static fields, properties, methods and constructors; static class; const |
| Go | idiom | package-level variables, constants and functions; no static members |
| Rust | native | associated functions and associated constants in impl; static items at module level |
| C | idiom | static variables at file scope; functions named with a prefix |
| C++ | native | static data members and member functions; static inline and static constexpr |
| Bash | n/a | global variables and functions, no types |
| PowerShell | native | static properties and methods in class definitions, called with [Type]::Name |
| SQL | n/a | a shared value is a row or a sequence, not a member |
| Regex | n/a | no types or members |
| HTML | n/a | no types or members |
| CSS | n/a | no types or members |
- Rust has no static fields in a type. An
implblock holds functions and constants: "All functions defined within an impl block are called associated functions",7 and an associated function withoutselfplays the part of a static method, as inString::from. A shared variable is astaticitem in the module. - Kotlin has no
statickeyword. "Companion objects allow you to define class-level functions and properties tied to a class",8 and code calls them on the class name, as inOrder.fromText("50"). - Go has no classes. The package is the unit that owns shared state, so a package-level variable plays the part of a static field, and a function such as
NewOrderplays the part of a static factory method.
class Order:
created = 0
def __init__(self):
type(self).register()
@classmethod
def register(cls):
cls.created += 1 # stores the sum on cls, which may be a subclass
class RushOrder(Order):
pass
Order()
Order()
RushOrder()
print(Order.created, RushOrder.created)
print("created" in vars(RushOrder))
2 3
True
- Verdict: native. A class attribute is a class variable,
@classmethodmakes a method that gets the class ascls, and@staticmethodmakes a function that gets neither the class nor an instance. cls.created += 1reads the value through the class and its bases, but it stores the sum oncls. The firstRushOrder()reads 2 fromOrderand stores 3 onRushOrder, so each class now has its own counter. WriteOrder.created += 1to keep one counter for the whole family of classes.
#include <iostream>
#include <string>
class Order {
public:
static constexpr double tax_rate = 0.2; // a constant static data member
static inline int created = 0; // one variable for the class
explicit Order(int amount) : id_(++created), amount_(amount) {}
static Order from_text(const std::string &text) { // no this pointer
return Order(std::stoi(text));
}
int id() const { return id_; }
double total() const { return amount_ * (1 + tax_rate); }
private:
int id_;
int amount_;
};
int main() {
Order a(100);
Order b = Order::from_text("50");
std::cout << a.id() << " " << b.id() << " " << Order::created << "\n";
std::cout << a.total() << " " << a.created << "\n";
}
1 2 2
120 2
- Verdict: native. A
staticdata member is one variable for the class, and astaticmember function has nothispointer. inlinelets the class definition also define the variable. Without it, one source file must defineint Order::created = 0;, or the program does not link.a.createdalso works and reads the same variable asOrder::created; the object is not used.
public class Main {
static final class Order {
static final double TAX_RATE = 0.2; // a constant: static and final
private static int created = 0; // a class variable, one for the class
private final int id; // an instance variable, one per order
private final int amount;
Order(int amount) {
created++;
this.id = created;
this.amount = amount;
}
static Order fromText(String text) { // a static factory method; no this
return new Order(Integer.parseInt(text));
}
static int created() {
return created;
}
double total() {
return amount * (1 + TAX_RATE);
}
}
public static void main(String[] args) {
Order a = new Order(100);
Order b = Order.fromText("50");
System.out.println(a.id + " " + b.id + " " + Order.created());
System.out.println(a.total() + " " + Order.TAX_RATE);
}
}
1 2 2
120.0 0.2
- Verdict: native. A
staticfield is a class variable and astaticmethod is a class method. Code calls them on the class name:Order.created(),Order.TAX_RATE. - A static method has no
this, sofromTextcannot readidoramount; it makes an instance and returns it.mainis itself a static method, because the program has noMainobject when it starts. - A static method is not a Python class method: it does not get the class as a parameter, and a subclass cannot override it, only hide it.
using System;
var a = new Order(100);
var b = Order.FromText("50");
Console.WriteLine($"{a.Id} {b.Id} {Order.Created}");
Console.WriteLine($"{a.Total()} {Money.Round(2.345)}");
class Order
{
public const double TaxRate = 0.2; // a const is static too
public static int Created { get; private set; } // a static property
public int Id { get; }
private readonly int amount;
public Order(int amount)
{
Created++;
Id = Created;
this.amount = amount;
}
public static Order FromText(string text) => new(int.Parse(text));
public double Total() => amount * (1 + TaxRate);
}
static class Money // a static class: no instances, only static members
{
public static double Round(double value) => Math.Round(value, 2);
}
1 2 2
120 2.35
- Verdict: native.
staticfields, properties and methods belong to the type, and aconstfield is static without the keyword. - A
static classsuch asMoneycannot have instances:new Money()is a compile error. It holds helper functions, likeSystem.Math. - A static member is reached only through the type name:
a.Createdis a compile error in C#, unlike in Java.
class Order {
static TAX_RATE = 0.2; // a static field, on the class object
static created = 0;
constructor(amount) {
Order.created++;
this.id = Order.created;
this.amount = amount;
}
static fromText(text) {
return new this(Number(text)); // this is the class that the call used
}
total() {
return this.amount * (1 + Order.TAX_RATE);
}
}
class RushOrder extends Order {}
const a = new Order(100);
const b = RushOrder.fromText("50");
console.log(a.id, b.id, Order.created, b.constructor.name);
console.log(a.total(), a.created, RushOrder.TAX_RATE);
1 2 2 RushOrder
120 undefined 0.2
- Verdict: native.
staticputs a field or method on the class object, not on the prototype, soa.createdisundefined. - In a static method,
thisis the class that the call used, soRushOrder.fromTextmakes aRushOrder. This is close to a Python class method. - Static members are inherited:
RushOrder.TAX_RATEfindsOrder.TAX_RATEthrough the prototype chain of the class objects.
package main
import (
"fmt"
"strconv"
)
// TaxRate and created play the part of static fields: one per package.
const TaxRate = 0.2
var created int
type Order struct {
ID int
amount int
}
// NewOrder and OrderFromText play the part of static methods.
func NewOrder(amount int) *Order {
created++
return &Order{ID: created, amount: amount}
}
func OrderFromText(text string) (*Order, error) {
n, err := strconv.Atoi(text)
if err != nil {
return nil, err
}
return NewOrder(n), nil
}
func (o *Order) Total() float64 { return float64(o.amount) * (1 + TaxRate) }
func main() {
a := NewOrder(100)
b, _ := OrderFromText("50")
fmt.Println(a.ID, b.ID, created)
fmt.Println(a.Total())
}
1 2 2
120
- Verdict: idiom. Go has no static members. A package-level variable, constant or function does the job, and the package, not the type, is the unit that owns it.
- The names say which type a function belongs to:
NewOrderandOrderFromText. Code in another package calls them asorders.NewOrder(100).
use std::sync::atomic::{AtomicU32, Ordering};
static CREATED: AtomicU32 = AtomicU32::new(0); // module-level: Rust has no static fields
struct Order {
id: u32,
amount: u32,
}
impl Order {
const TAX_RATE: f64 = 0.2; // an associated constant
fn new(amount: u32) -> Order { // an associated function: no self
let id = CREATED.fetch_add(1, Ordering::Relaxed) + 1;
Order { id, amount }
}
fn from_text(text: &str) -> Option<Order> {
text.parse().ok().map(Order::new)
}
fn created() -> u32 {
CREATED.load(Ordering::Relaxed)
}
fn total(&self) -> f64 { // a method: it has self
self.amount as f64 * (1.0 + Self::TAX_RATE)
}
}
fn main() {
let a = Order::new(100);
let b = Order::from_text("50").unwrap();
println!("{} {} {}", a.id, b.id, Order::created());
println!("{} {}", a.total(), Order::TAX_RATE);
}
1 2 2
120 0.2
- Verdict: native. An
implblock holds associated functions with noself, called asOrder::new, and associated constants, but no associated variables. - A changing value shared by all orders is a
staticitem at the module level. Astaticmust be safe to share between threads, so the counter is anAtomicU32; astatic mutwould needunsafecode at each use.
Variations and related ideas
- Static classes and modules. A C#
static classholds only static members, and "a static class can't be instantiated".2System.Mathis one. A Python or JavaScript module, a Go package and a Rust module do the same job without a class. - Static factory methods. A static method that returns an instance, such as
Order.fromTextor RustOrder::new, can have a name, can return a cached instance and can return a subclass. See static factory method. - Constants. A Java
static finalfield, a C#const, a C++static constexprmember and a Rust associatedconstare static members whose value cannot change. They are the safest kind, because shared state that does not change needs no lock. - Per-thread statics. C#
[ThreadStatic], JavaThreadLocal, C++thread_localand Rustthread_local!give each thread its own copy: "Static fields marked with ThreadStaticAttribute have one copy per thread."2 - Singletons and global data. A static field that holds an object is the base of the singleton pattern. A changing static field is global data with a class name in front of it.
Pitfalls
- Assignment through an instance in Python.
self.count += 1reads the class variable, but it stores the sum in an attribute of the instance, so the class variable does not change. A mutable class attribute has the opposite problem:self.names.append(x)changes the one list that all instances share. The Python tutorial warns about such a list: it is a "mistaken use of a class variable",9 because "a single list would be shared by all Dog instances".
class Counter:
count = 0
names = [] # one list for the class and every instance
def __init__(self, name):
self.count += 1 # reads Counter.count, then stores the sum on the instance
self.names.append(name) # changes the shared list
a = Counter("a")
b = Counter("b")
print(Counter.count, a.count, b.count)
print(Counter.names, a.names is b.names)
0 1 1
['a', 'b'] True
clsin a Python class method is the subclass. "If a class method is called for a derived class, the derived class object is passed as the implied first argument."4 Socls.created += 1makes a separate counter on each subclass. Write the class name,Order.created += 1, for one counter.- A static method does not override. A Java or C# static method with the same name in a subclass hides the method of the base class. A call is bound by the declared type at compile time, not by the object at run time.
- Shared state between threads. Two threads that do
created++on one static field can lose an update. Use an atomic counter or a lock, or keep the field constant. Rust makes this a compile error: astaticmust be safe to share, so a counter is an atomic type. - Hidden dependencies and tests. A method that reads a static field depends on a value that does not show in its parameters, and that keeps its value from one test to the next. See the pitfalls of Use a singleton.
- Initialization order in C++. Static data members in different source files are initialized in an order that the standard does not fix. One that uses another in its initializer can see it before it has its value.
Cost
A static field is at a fixed address, so a read or a write costs the same as for a global variable, with no object to load first. A static method call is a direct call with no receiver and no dynamic dispatch, so the compiler can inline it. The first use of a class in Java or C# can run its static initializer, and a C++ function-local static has a guard check at each call; after the first call, these checks cost little. In Python and JavaScript, a class attribute is found by a lookup at run time, as for other attributes. Memory: a static field takes its space once, not once per instance.
History
Smalltalk-80 made classes objects: "Smalltalk-80 added metaclasses",5 so a class could have its own variables and methods, which Smalltalk calls class variables and class methods. C++ used the keyword static for the same idea, because a static data member has static storage duration, like a static variable in C. cppreference puts it this way: "Static members of a class are not associated with the objects of the class".3 A static data member is an independent variable, and a static member function is a regular function in the scope of the class. Java and C# kept the C++ keyword, and Python added classmethod and staticmethod as built-in functions. JavaScript added static methods with classes, and later static fields; MDN gives the usual jobs: "Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances."6 Kotlin, Go and Rust dropped the keyword and use companion objects, packages and modules instead.
References
- Understanding Class Members, The Java Tutorials, Class Variables; Class Methods; Constants
- Static Classes and Static Class Members, C# programming guide, Static Members
- static members, cppreference.com, Explanation; Static member functions; Static data members
- Built-in Functions, The Python Standard Library, classmethod; staticmethod
- Smalltalk, Wikipedia, Reflection
- static, JavaScript reference, MDN, Description
- Methods, The Rust Programming Language, Associated Functions
- Object declarations and expressions, Kotlin documentation, Companion objects
- 9. Classes, The Python Tutorial, 9.3.5 Class and Instance Variables
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 FVBDQB Edit this page History Report an error Markdown