AlgoViz

Static methods and fields

medium 45 min

A static member belongs to the class and not to one object.

Watch lesson4:36

Where it shows up

The same pattern appears across everyday software.

  • Java Math

    A final class with static methods for numeric operations and the constants PI and E. No object of it is ever needed.

  • Java Integer.valueOf

    A static factory. The documentation says it always caches values from -128 to 127, which a constructor could not do.

  • Java LocalDate.now

    Offered with and without a Clock. The variant with a Clock lets tests choose the day.

  • Java Runtime

    The documentation says that every Java application has a single instance, obtained from the static method getRuntime.

  • Python class methods

    The built-in classmethod passes the class. datetime.fromtimestamp and dict.fromkeys are alternative constructors made with it.

  • Python tutorial

    It shows the trap of a list as class variable: all dogs share the same tricks.

  • Django managers

    Every model class gets a Manager named objects by default. Queries start at the class, not at one row.

  • Kotlin

    The documentation offers companion objects: members called by the class name that live in a real object.

  • C++ FAQ

    It describes the static initialization order problem as a subtle way to crash a program.

  • Gunicorn

    Its design page describes a pre-fork worker model with several processes. Each has its own copy of every class variable.