Overriding a property definition in a subclass

In contrast to standard instance variables, property get and property set methods are virtual. You can override virtual property methods in subclasses and implement them from interfaces. You can even call the superclass’s property get or property set methods.

The following code is the superclass.
class TemperatureInCelsius {
  protected var _temp : float as Temperature

  property get FreezingText () : String {
    return (_temp <= 0 ? "freezing!" : "NOT freezing!")
  }

  public function howHot()   {
    print ("In Celsius it is ${_temp} and it is ${FreezingText}")
  }
}
The following code shows how you override a property in a subclass.
// Subclass for Kelvin (which is Celsius - 273)
class TemperatureInKelvin extends TemperatureInCelsius {

  property get TemperatureInCelsius() : float {
    return super.Temperature
  }
  override property get Temperature() : float {
    return super.Temperature + 273   // Convert Celsius to Kelvin
  }
  override property set Temperature(t : float ) {
    super.Temperature = t - 273      // Convert Kelvin to Celsius
  }
}

The overridden property get method first calls the implicitly defined property get method from the superclass, which gets the class variable _temp, and then adds a value. This property get method does not change the value of the class variable _temp, but code that accesses the Temperature property from the subclass gets a different value.

To test overriding a property definition in a subclass, create the classes in the previous code. Next, run the following code in the Gosu Scratchpad:
var cTemp = new TemperatureInCelsius()
var kTemp = new TemperatureInKelvin()

cTemp.Temperature = 123
kTemp.Temperature = 123

cTemp.howHot()
kTemp.howHot()

print("Temperature in Kelvin: ${kTemp.Temperature}")
print("Temperature in Celsius: ${kTemp.TemperatureInCelsius}")
This code prints:
In Celsius it is 123 and it is NOT freezing!
In Celsius it is -150 and it is freezing!
Temperature in Kelvin: 123
Temperature in Celsius: -150