Inheritance
Extend classes with `<` and call superclass methods with `super`.
Inherit with class Child < Parent: angle bracket, not extends.
Use super.methodName() inside a subclass to invoke the parent's implementation.
this always refers to the current instance (the receiver), including inside inherited methods.
Override a method
Subclass with `<` and call the parent implementation via `super.method()`.
class Animal {
speak() {
print "...";
}
}
class Dog < Animal {
speak() {
super.speak();
print "Woof!";
}
}
Dog().speak();output
... Woof!
Override init
Subclasses define their own `init`: set fields on `this` directly.
class Point {
init(x, y) {
this.x = x;
this.y = y;
}
}
class ColorPoint < Point {
init(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
}
}
var p = ColorPoint(1, 2, "red");
print p.color;output
red