Product SiteDocumentation Site

4.2.8. Public and Private Methods

A method can be public or private. Any object can send a message that runs a public method. A private method can only be invoked from specific calling contexts. These contexts are:
  1. From within a method owned by the same class as the target. This is frequently the same object, accessed via the special variable SELF. Private methods of an object can also be accessed from other instances of the same class (or subclass instances).
  2. From within a method defined at the same class scope as the method. For example:

    Example 4.10. Referencing methods

    
    ::class Savings
    ::method newCheckingAccount CLASS
      instance = self~new
      instance~makeChecking
      return instance
    
    ::method makeChecking private
      expose checking
      checking = .true
    
    

    The newCheckingAccount CLASS method is able to invoke the makeChecking method because the scope of the makeChecking method is .Savings.
  3. From within an instance (or subclass instance) of a class to a private class method of its class. For example:

    Example 4.11. Referencing methods

    
    ::class Savings
    ::method init class
      expose counter
      counter = 0
    
    ::method allocateAccountNumber private class
      expose counter
      counter = counter + 1
      return counter
    
    ::method init
      expose accountNumber
      accountNumber = self~class~allocateAccountNumber
    
    

    The instance init method of the Savings class is able to invoke the allocateAccountNumber private method of the .Savings class object because it is owned by an instance of the .Savings class.
Private methods include methods at different scopes within the same object. This allows superclasses to make methods available to their subclasses while hiding those methods from other objects. A private method is like an internal subroutine. It shields the internal information of an object to outsiders, but allowing objects to share information with each other and their defining classes.