Create an interface with getters, setters, and methods
About this task
To create an interface with getters, setters and methods, perform the following general steps:
Procedure
- In the package for your new type, create a Gosu interface file with a .gs file extension.
-
Add property declarations and method signatures:
- To provide data from a variable or property on an instance of this type, use
property getter
syntax:
property get PROPERTY_NAME() : TYPE - To set the value of a variable or property on an instance of this type, use
property setter syntax:
property set PROPERTY_NAME(TYPE) - To provide a callable method on an instance of this type, use the syntax:
public function METHOD_NAME(ARG_LIST) : TYPE
- To provide data from a variable or property on an instance of this type, use
property getter
syntax:
Example
This example declares an interface called DemoInterface that has the
following features:
Nameproperty of typeString- count method, which takes one
Stringparameter and returns aintvalue
Start by creating a file defining the interface:
package examples.pl.gosu.intf
interface DemoInterface {
property get Name() : String
property set Name(n : String)
public function count(s : String) : int
}
Create a class implementing the interface:
uses examples.pl.gosu.intf.DemoInterface
class MyClass implements DemoInterface {
var _name : String
override property get Name() : String {
return "name: " + _name
}
override property set Name(n:String) {
_name = n
}
override function count(s : String) : int {
return s.length()
}
}
The following code creates an instance of the class and tests its properties and method:
var myObject = new MyClass()
myObject.Name = "Andy Applegate"
print(myObject.Name)
print(myObject.count(myObject.Name))
Output:
name: Andy Applegate
20
