Programming Search⌘K

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
Output
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-local static. 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 allow a.created through an instance, C# does not, and in JavaScript "Static properties cannot be directly accessed on instances of the class."6

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiomA 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
JavaScriptNative
TypeScriptNativeAs 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.
GoIdiom
RustNative
KotlinNativeNo 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.
SQLDoes not applyA table has no class-level members; a shared value is a row in another table or a sequence.
BashDoes not applyBash has global variables and functions but no types that own them.
PowerShellNativeStatic 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.
HTMLDoes not applyHTML has no types or members; static members of DOM classes belong to JavaScript.
CSSDoes not applyCSS has no types or members.
Regular expressionsDoes not applyA 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 impl block holds functions and constants: "All functions defined within an impl block are called associated functions",7 and an associated function without self plays the part of a static method, as in String::from. A shared variable is a static item in the module.
  • Kotlin has no static keyword. "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 in Order.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 NewOrder plays the part of a static factory method.
PythonGitHub
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))
Output
2 3
True
  • Verdict: native. A class attribute is a class variable, @classmethod makes a method that gets the class as cls, and @staticmethod makes a function that gets neither the class nor an instance.
  • cls.created += 1 reads the value through the class and its bases, but it stores the sum on cls. The first RushOrder() reads 2 from Order and stores 3 on RushOrder, so each class now has its own counter. Write Order.created += 1 to 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";
}
Output
1 2 2
120 2
  • Verdict: native. A static data member is one variable for the class, and a static member function has no this pointer.
  • inline lets the class definition also define the variable. Without it, one source file must define int Order::created = 0;, or the program does not link.
  • a.created also works and reads the same variable as Order::created; the object is not used.
JavaGitHub
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);
  }
}
Output
1 2 2
120.0 0.2
  • Verdict: native. A static field is a class variable and a static method is a class method. Code calls them on the class name: Order.created(), Order.TAX_RATE.
  • A static method has no this, so fromText cannot read id or amount; it makes an instance and returns it. main is itself a static method, because the program has no Main object 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);
}
Output
1 2 2
120 2.35
  • Verdict: native. static fields, properties and methods belong to the type, and a const field is static without the keyword.
  • A static class such as Money cannot have instances: new Money() is a compile error. It holds helper functions, like System.Math.
  • A static member is reached only through the type name: a.Created is a compile error in C#, unlike in Java.
JavaScriptGitHub
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);
Output
1 2 2 RushOrder
120 undefined 0.2
  • Verdict: native. static puts a field or method on the class object, not on the prototype, so a.created is undefined.
  • In a static method, this is the class that the call used, so RushOrder.fromText makes a RushOrder. This is close to a Python class method.
  • Static members are inherited: RushOrder.TAX_RATE finds Order.TAX_RATE through 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())
}
Output
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: NewOrder and OrderFromText. Code in another package calls them as orders.NewOrder(100).
RustGitHub
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);
}
Output
1 2 2
120 0.2
  • Verdict: native. An impl block holds associated functions with no self, called as Order::new, and associated constants, but no associated variables.
  • A changing value shared by all orders is a static item at the module level. A static must be safe to share between threads, so the counter is an AtomicU32; a static mut would need unsafe code at each use.
  • Static classes and modules. A C# static class holds only static members, and "a static class can't be instantiated".2 System.Math is 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.fromText or Rust Order::new, can have a name, can return a cached instance and can return a subclass. See static factory method.
  • Constants. A Java static final field, a C# const, a C++ static constexpr member and a Rust associated const are 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], Java ThreadLocal, C++ thread_local and Rust thread_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 += 1 reads 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)
Output
0 1 1
['a', 'b'] True
  • cls in 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 So cls.created += 1 makes 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: a static must 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

  1. Understanding Class Members, The Java Tutorials, Class Variables; Class Methods; Constants
  2. Static Classes and Static Class Members, C# programming guide, Static Members
  3. static members, cppreference.com, Explanation; Static member functions; Static data members
  4. Built-in Functions, The Python Standard Library, classmethod; staticmethod
  5. Smalltalk, Wikipedia, Reflection
  6. static, JavaScript reference, MDN, Description
  7. Methods, The Rust Programming Language, Associated Functions
  8. Object declarations and expressions, Kotlin documentation, Companion objects
  9. 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.

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/FVBDQB/text.yaml