A field is a variable associated with a class, when the field is static, or with an instance of a class, otherwise.
Fields can be declared both in the class declaration and in its implementation. Each field, however, can only be declared once.
Stack = class[X] private Items: Array[X]; Count, Capacity: Integer; // ... end;
A field declared in an implementation section is considered as a private field:
implementation for Stack[X] is var Items: Array[X]; // ...
Field declarations inside may be optionally preceded by the var keyword. You can add the static modifier for declaring static private fields, both in a class declaration and in its implementation.
A field declaration may be followed by an initialization expression:
implementation for Stack[X] is var Items: Array[X] = new Array[X](128);
You can't use any instance member in a field initializer. Field initializers are evaluated before the constructor from the base class is called.
Static fields can also have an initializer. In that case, the initializer expression may refer to other static members, both from the declaring type or from any other type. Static field initializers are executed in their declared order:
MyClass = class public static A: Integer = B + 1; static B: Integer = A + 1; end;
In the above class, A is initialized with 1, since B has not yet been initialized and it holds the default value for integers. Then, B is initialized with 2, because A at that point, A has already been initialized.
You can also declare read only fields:
Stack = class[X] private Capacity: Integer; readonly; // ... end;
A read only field cannot be modified except inside a constructor from its class:
constructor Stack(Capacity: Integer); begin Self.Capacity := Capacity; // ... end;
You can also use a field initializer with a read only field.
Classes and records can declare static read only fields that will behave as constants. For instance:
Vector = record public constructor(X, Y, Z: Double); public static Zero: Vector = new Vector; readonly; static XAxis: Vector = new Vector(1, 0, 0); readonly; static YAxis: Vector = new Vector(0, 1, 0); readonly; static ZAxis: Vector = new Vector(0, 0, 1); readonly; end;
We could have initialized those static read only fields in a static constructor, as an alternative.
The Freya Programming Language
Type declarations
Type members
Constant members
Constructors
Methods
User defined operators
Iterators
Properties
Events