Users › 05 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.
%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
}
pub. They can only be
declared, never initialized inline; constructors do that. Field
access always goes through this.._ makes one private.
Methods cannot be marked pub.c.x vs c.x()).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
}
___init and the return type must be
void.new selects the
overload by argument types (exact match first, then the smallest implicit
promotion; ambiguity is a compile error).%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
}
Config.setName("prod"), Config.name().new, and you cannot declare a variable of the singleton
type. To pass it around, pass it as an interface it implements.%nativesimple is the same shape, implemented by a native
plugin.%subWhen 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).