Object-Oriented Programming in FreeM

From FreeM Wiki
Revision as of 18:29, 29 November 2024 by Smw (talk | contribs)
Jump to navigation Jump to search

Classes

In FreeM, a class is defined by a routine. For instance, the STRING class (built into FreeM) is contained in the %STRING routine.


Constructors

A constructor must be the first entry point in a class definition, and the label name must match the routine name, and it must take two arguments, THIS and INIT. THIS represents the instance of the object being accessed, and INIT represents an initializer that can be used to assign an initial value to the object when instantiating the class.

A constructor looks like this:

%FRACTION(THIS,INIT):OBJECT ;
   S THIS("NUMERATOR"):PRIVATE=$P(INIT,"/",1)
   S THIS("DENOMINATOR"):PRIVATE=$P(INIT,"/",2)
   Q

The general syntax of a constructor is <routine-name>(THIS,INIT)[:<superclass>], where superclass represents the name of a class from which this class should inherit. In the above example, the FRACTION class inherits from the OBJECT class. Note that this is not strictly necessary in this case, as all classes automatically inherit from OBJECT.

Destructors

A destructor is called when you KILL an instance variable. It must be named DESTROY, and must take one argument (THIS). The destructor should be used to clean up any resources used by class methods.

Inheritance Rules

Every class you create will automatically inherit the methods and functionality of the OBJECT class, supplied with FreeM.

When attempting to call a method, FreeM will first search the class routine for a matching entry point, and then follow the inheritance chain upwards until a matching entry point is found. If the final class in the chain does not have a matching entry point, FreeM will try to find a matching entry point in the OBJECT class.

Instantiating Classes

To instantiate a class (i.e., create an object from a certain class), you will use the NEW command as follows:

NEW MYSTR=$#^%STRING("myString")

This will create a local variable called MYSTR of type STRING, and initialize it with the value myString.