Users › 05 Classes and singletons

Classes and singletons

Define classes with fields, constructors and methods; learn the three object shapes the language offers, and the one that is private to a file.

1. A class

%class com.example.Counter
    int _n                      // private field (default)

    void ___init() {            // constructor
        this._n = 0
    }

    void bump() {               // public method
        this._n = this._n + 1
    }

    int value() {
        return this._n
    }

2. Constructors

void ___init(String name, int age) {
    this._name = name
    this._age = age
}

void ___init(String name) {     // overloads are allowed
    this._name = name
    this._age = 0
}

3. Singletons: %simple

%simple com.example.Config
    String _name

    void ___init() {            // no parameters
        this._name = "dev"
    }

    void setName(String name) {
        this._name = name
    }

    String name() {
        return this._name
    }

4. File-private classes: %sub

When a class only exists to support one file, declare it as %sub after the primary declaration and use it as $Name. Members are public within the file; the class never appears in a public signature.

%simple com.example.classes.Demo implements Main
    #import Std
    int run(int argc, String[] argv) Main@run {
        $Counter c = new $Counter()
        $Counter d = new $Counter(10)
        c.bump()
        c.bump()
        d.bump()
        $Pair p = new $Pair(1, 2)
        Std.print("c=", c.value(), " d=", d.value(), " sum=", p.sum(), "\n")
        return 0
    }

%sub Counter
    int n

    void ___init() {
        this.n = 0
    }

    void ___init(int n) {
        this.n = n
    }

    void bump() {
        this.n = this.n + 1
    }

    int value() {
        return this.n
    }

%sub Pair
    int a
    int b

    void ___init(int a, int b) {
        this.a = a
        this.b = b
    }

    int sum() {
        return this.a + this.b
    }
c=2 d=11 sum=3

In the task-list example, Task is a %class with a constructor and a private field, while CapacityException is another %class (chapter 8 explains why it needs to be a full class).