Creating Classes Using Messages

You can create a class using messages as well as directives. Though classes are available only to the program that creates them, there are occasions when this is useful and public availability is not required. The following sections demonstrate the message technique using the Savings Account example previously shown with directives.

Defining a New Class

To define a new class using messages, you send a SUBCLASS message to the new class's superclass. That is, you send the message to the class that precedes the new class in the hierarchy. To define a subclass of the Object class called Account, you enter:

account = .object~subclass("Account")

Here, .object is a reference to the Rexx Object class. .object is an environment symbol indicating the intention to create a new class that is a subclass of the Object class. Environment symbols represent objects in a directory of public objects, called the Environment object. These public objects are available to all other objects, and include all the classes that Rexx provides. Environment symbols begin with a period and are followed by the class name. Thus the Object class is represented by .object, the Alarm class by .alarm, the Array class by .array, and so on.

The twiddle (~) is the "message send" symbol, subclass is a method of Class, and the string identifier in parentheses is an argument of SUBCLASS that names the new class, Account.

Adding a Method to a Class

You use the DEFINE method to define methods for your new class. To define a TYPE method and a NAME= method, you enter:

account~define("TYPE", "return ""an account""")
account~define("NAME=", "expose name; use arg name")

Defining a Subclass of the New Class

Using the SUBCLASS method, you can define a subclass for your new class and then a method for that subclass. To define a Savings subclass for the Account class, and a TYPE method for Savings, you enter:

savings = account~subclass("Savings Account")
savings~define("TYPE", "return ""a savings account""")

Defining an Instance

You use the NEW method to define an instance of the new class, and then call methods that the instance inherited from its superclass. To define an instance of the Savings class named "John Smith," and send John Smith the TYPE and NAME= messages to call the related methods, you enter:

newaccount = savings~new
say newaccount~type
newaccount~name = "John Smith"