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

  1. In the package for your new type, create a Gosu interface file with a .gs file extension.
  2. 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

Example

This example declares an interface called DemoInterface that has the following features:

  • Name property of type String
  • count method, which takes one String parameter and returns a int value

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