AlgoViz

Static methods and fields

medium 45 min

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

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:36

See it run

One copy or many: where a value lives, who sees a change, and how far one reaches.

Operations

The shared counter

The class exists before its objects.

Step 1 of 5

Class loaded

maincallerCirclethe class itselfPI3.14159...count0count()0

No circle yet. The class has its two fields, and can be asked.

Step 1: Class loaded

class Circle:    PI = math.pi    _count = 0    def __init__(self, name, radius):        self.name, self.radius = name, radius        Circle._count += 1    @classmethod    def count(cls): return cls._countCircle.count()first = Circle("First", 2)second = Circle("Second", 3)Circle.count()
Good for
Constants, counts for learning
Costs
One copy
Copies of PI for 2 objects
1

Write the class name when you change a class attribute in Python.

In the real world

The same static methods and fields doing real jobs. Pick one and step through it.

Order numbers from a static field, in a service with two processes.

Step 1 of 5

Start

usersordersprocess 1own classstatic next1process 2own classstatic next1

Both processes load the class. Each has its own static field.

Step 1: Start

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A list on the class

    critical

    All objects share one list.

    Wrong
    class Player:    friends = []
    Right
    class Player:    def __init__(self): self.friends = []
  • this in a static method

    minor

    There is no instance. It does not compile in Java.

    Wrong
    static void print() {    System.out.println(this.name); }
    Right
    static void print(Player p) {    System.out.println(p.name); }
  • Called through an object

    minor

    It looks as if the object mattered.

    Wrong
    MyClass obj = new MyClass();obj.staticMethod();
    Right
    MyClass.staticMethod();
  • Lock on this for a static field

    critical

    Two objects have two locks, the field is one.

    Wrong
    synchronized void hit() { count++; }   // count is static
    Right
    static synchronized void hit() { count++; }
  • A hidden clock

    major

    Nobody can test the last day of the year.

    Wrong
    static boolean isWeekend() { ... LocalDate.now() ... }
    Right
    static boolean isWeekend(LocalDate date) { ... }
  • A cache without an end

    major

    A static collection keeps everything alive.

    Wrong
    static Map<User, Session> all = new HashMap<>();
    Right
    final class Sessions { /* limit and expiry */ }

Interview tips

  • One sentence

    • This player: instance
    • Every player: static
    • Changes: an owner
  • Three good uses

    • Constants
    • Pure helpers
    • Named constructors
  • Say the scope

    • Thread, request
    • Process, machine
    • System
  • Move away slowly

    • Static forwards to an object
    • Callers move
    • Close the door