More property examples

The following examples demonstrate how to create and use Gosu class properties and their getter and setter methods.

The examples use two classes, one of which extends the other.

The class myFirstClass:

package mypackage

class MyFirstClass {

  // Explicit property getter for Fred
  property get Fred() : String   { 
    return "myFirstClass" 
  } 
}

The class mySecondClass:

package mypackage

class MySecondClass extends MyFirstClass {

  // Exposes a public F0 property on _f0 
  private var _f0 : String as F0 

  // Exposes a public read-only F1 property on _f1 
  private var _f1 : String as readonly F1 

  // Simple variable with explicit property get/set methods 
  private var _f2 : String 

  // Explicit property getter for _f2 
  property get F2() : String { 
    return _f2 
  } 

  // Explicit property setter for _f2, visible only to classes in this package 
  internal property set F2( value : String ) { 
    _f2 = value 
  } 

  // A simple calculated property (not a simple accessor) 
  property get Calculation() : Number { 
    return 88 
  } 

  // Overrides MyFirstClass's Fred property getter 
  property get Fred() : String { 
    return super.Fred + " suffix" 
  } 
}

Create the classes, and then try the following lines in Gosu Scratchpad to test these classes.

First, create an instance of your class:

var test = new mypackage.MySecondClass()

Assign a property value. This code internally calls a hidden method to assign "hello" to variable _f0:

test.F0 = "hello"

The following line is invalid because f1 is read-only:

// This line gives a compile error.
test.F1 = "hello" 

Get a property value. This code indirectly calls the mySecondClass property getter function for F2:

print( test.F2 ) // Prints null because the property is not set yet

The following line is invalid because F2 is not visible outside of the package namespace of MySecondClass. The F2 property is publicly read-only.

// This line gives a compile error. 
test.F2 = "hello"

Print the Calculation property:

print( test.Calculation ) // Prints 88

The following line is invalid because Calculation is read-only. This property does not have a setter function:

// This line gives a compiler error. 
test.Calculation = 123 

Demonstrate that properties can be overridden through inheritance because properties are virtual:

print( test.Fred ) // Prints "myFirstClass suffix"