Static functions and properties

Learning Objectives

Lesson

The static keyword

The static keyword can be applied to a function/method or a property of a class.

A static function/method does not use any instance specific values, instead it executes logic on the data passed in as function/method arguments. Static functions/methods are often 'utility' functions, for example finding the maximum of 2 numbers. We call a static function/method using the name of the class, for example:

Math.max(1, 2);

Static properties belong to the class as a whole rather than one specific instance. We often use static properites to hold constant values, for example, the value of PI.

static const PI = 3.14
private static PI:number = 3.14
private static final double PI = 3.14;

Static functions in the Airport domain

Imagine we have an air traffic control system to keep track of all the planes using 2 runways. We have a rule that only a certain number of planes can be on either of the 2 runways at a time, otherwise our air traffic controllers will get overloaded!

We'll create 2 instance of a Runway class - one for the landing planes and one for departing planes. We'll add a static property to hold a constant representing the maximum number of planes allowed on the runway plus a static property holding a list of all the planes currently on either of the runways (note this code is not thread safe, it is shown for example purposes only). We'll then add a static function/method to add a plane to the runway.

class Runway {
    static MAX_PLANES_ALLOWED_ON_ALL_RUNWAYS = 100;
    static planes = [];

    name;

    constructor(name) {
        this.name = name
    }
    
    add(plane) {

        if (Runway.planes.length>Runway.MAX_PLANES_ALLOWED_ON_ALL_RUNWAYS) {
            throw new Error ("runways at full capacity!")
        }
        Runway.planes.push(plane)
    }
}
TODO
public class Runway {
    private static final int MAX_PLANES_ALLOWED_ON_ALL_RUNWAYS = 100;

    private String name;
    private static List<Plane> planes = new ArrayList<Plane>();

    public Runway(String name) {
        this.name = name;
    }

    public void add(Plane plane) throws Exception {

        if (this.planes.size()>Runway.MAX_PLANES_ALLOWED_ON_ALL_RUNWAYS) {
            throw new Exception ("runways at full capacity!");
        }
        this.planes.add(plane);
    }
}

Assignment

Assignment extensions tasks

Research OO languages which use static classes - what does the static keyword mean when applied to a class?

Additional resources