Product Site

4.2. Creating and Using Classes and Methods

You can define a class using either directives or messages.

To define a class using directives, you place a ::CLASS directive after the main part of your source program:
::class "Account"

This creates an Account class that is a subclass of the Object class. Object is the default superclass if one is not specified. See Section 5.1.4, “Object Class” for details. The string "Account" is a string identifier for the new class. The string identifier is both the internal class name and the name of the environment symbol used to locate your new class instance.

Now you can use ::METHOD directive to add methods to your new class. The ::METHOD directives must immediately follow the ::CLASS directive that creates the class.
Example 4.3. Adding a method
::method type
  return "an account"

::method "name="
  expose name
  use arg name

::method name
  expose name
  return name

This adds the methods TYPE, NAME, and NAME= to the Account class.

You can create a subclass of the Account class and define a method for it:
Example 4.4. Adding a method
::class "Savings" subclass account
::method type
return "a savings account"

Now you can create an instance of the Savings class with the new method and send TYPE, NAME, and NAME= messages to that instance:
Example 4.5. Invoking a method
asav = .savings~new
say asav~type
asav~name = "John Smith"

The Account class methods NAME and NAME= create a pair of access methods to the account object variable NAME. The following directive sequence creates the NAME and NAME= methods:
Example 4.6. Defining SET and GET methods
::method "name="
  expose name
  use arg name

::method name
  expose name
  return name

You can replace this with a single ::ATTRIBUTE directive. For example, the directive
::attribute name

adds two methods, NAME and NAME= to a class. These methods perform the same function as the NAME and NAME= methods in the original example. The NAME method returns the current value of the object variable NAME; the NAME= method assigns a new value to the object variable NAME.

In addition to defining operational methods and attribute methods, you can add "constant" methods to a class using the ::CONSTANT directive. The ::CONSTANT directive will create both a class method and an instance method to the class definition. The constant method will always return the same constant value, and can be invoked by sending a message to either the class or an instance method. For example, you might add the following constant to your Account class:
::constant checkingMinimum 200

This value can be retrieved using either of the following methods
Example 4.7. Retrieving method values
  say .Account~checkingMinimum    -- displays "200"
  asave = .savings~new
  say asave~checkingMinimum       -- also displays "200"