Overview of Gosu classes and properties
Gosu supports object-oriented programming using classes, interfaces and polymorphism. Also, Gosu is fully compatible with Java types, so Gosu types can extend Java types, or implement Java interfaces.
At the top of a class file, use the package keyword to declare the
package of this class. A package
defines a namespace. To import specific classes or package hierarchies
for later use in the file, add lines with the uses keyword. This is equivalent
to the Java import statement.
Gosu supports exact type names, or hierarchies with the * wildcard symbol:
uses gw.example.MyClass // Exact type
uses gw.example.queues.jms.* // Wildcard symbol * specifies a hierarchy
To create a class, use the class keyword, followed by the
class name, and then define the variables, then the methods for the class.
To define one or more constructor (object instance initialization) methods,
use the construct keyword.
The following example shows a simple class with one constructor that
requires a String argument:
class ABC {
construct(id : String) {
}
}
You can optionally specify that your class implements one or more interfaces.
To create a new instance of a class, use
the new keyword in the
same way as in Java. Pass any constructor arguments in parentheses. Gosu
decides what version of the class constructor to use based on the number
and types of the arguments. For example, the following calls the constructor
for the ABC class defined earlier in this topic:
var a = new ABC("My initialization string")Gosu improves on this basic pattern and introduces a standard compact syntax for property initialization during object creation. For example, suppose you have the following Gosu code:
var myFileContainer = new my.company.FileContainer()
myFileContainer.DestFile = jarFile
myFileContainer.BaseDir = dir
myFileContainer.Update = true
myFileContainer.WhenManifestOnly = ScriptEnvironment.WHEN_EMPTY_SKIP
After the first line, four more lines contain the object variable name, which is repeated information.
You can use Gosu object initializers to simplify this code to only a couple of lines:
var myFileContainer = new my.company.FileContainer() { :DestFile = jarFile, :BaseDir = dir,
:Update = true, :WhenManifestOnly = ScriptEnvironment.WHEN_EMPTY_SKIP }
You can also choose to list each initialization on its own line, which uses more lines but is more readable:
var myFileContainer = new my.company.FileContainer() {
:DestFile = jarFile,
:BaseDir = dir,
:Update = true,
:WhenManifestOnly = ScriptEnvironment.WHEN_EMPTY_SKIP
}
Unlike in Java, for special case usage you can optionally
omit the type name entirely in a new
expression if the type is known from its context. Do not omit the type
name in typical code. However, for dense hierarchical structure, omitting
the type name can make your Gosu code more readable.
See also
