Constructors
new MyClass() calls the MyClass constructor for
initialization or other actions. To create a constructor, name the method
construct. Do not use the function keyword. If
you do not need a class constructor, you do not need to create the
construct method.public
scope by default.For example, the following class contains one constructor that takes no arguments:
package doc.example
class Tree {
construct() {
print("I just created a Tree object!")
}
}
You can create constructors that take arguments, in the same way as for other methods. Any code that instantiates
that object can pass arguments to the new expression. For example, the following class contains a
constructor requiring a parameter:
package doc.example
class Tree {
var _name : String // A private class var
// A public constructor
construct(name : String) {
_name = name
print("I just created a ${_name} Tree object!")
}
}
var t = new Tree("Ginkgo")I just created a Ginkgo Tree object!
If the class constructors all take one or more arguments, any code that instantiates the class must provide a
parameter list. Failing to pass arguments to a new expression for this class produces a
compilation error.
Accessing the constructor of a parent class
If your class extends another class, your constructor can call the constructor of its parent class by using the
super keyword, followed by parentheses. This statement must be the first statement in the
subclass constructor. For example, the following code calls the parent-class constructor, and then performs
additional work.
package doc.example
class Tree extends Plant {
construct() {
super()
print("I just created a Tree object!")
}
}
If you call super() with no arguments between the parentheses, Gosu calls the no-argument
constructor of the parent class. If you call
super(parameter_list), Gosu calls the parent-class
constructor that matches the provided parameter list. You can call a parent-class constructor with different
number of arguments or different types than the current constructor.
For every constructor that you write, Gosu always calls a version of the parent-class constructor, even if you
omit an explicit reference to super(). If your class does not call the superclass constructor
explicitly, Gosu attempts to use the no-argument superclass constructor:
- If a no-argument constructor exists in the parent class, Gosu calls that constructor, which is equivalent to
the code
super(). - If a no-argument constructor does not exist in the parent class, Gosu throws a
no default constructorcompilation syntax error.
