Anonymous methods

 

Definition

An anonymous method is a method without a name or parameters.  Its body is embedded in a named method or in another anonymous method.  The beginning and the end of the body are indicated respectively by "{" and "}".

 

Local variables can be defined before the first instruction.

 

Instructions can access local variables and method parameters.  However, there is no direct access to the instance or class attributes of embedding objects.  The use of "super" is not permitted.

 

 

Diffusion to an object

An anonymous method is always distributed to the object that comes syntactically before the "{" at the beginning of the body.  In the body of the anonymous method, the "this" variable is initialized with this object or successively with each of these elements if it is a set.

 

 

Example 1

We are now going to concatenate all the attributes of a class in a character String.

 

Note:      This program can be run with the "printAttribute" command on a class.

 

Class:printAttribute()

{

   String line;

   PartAttribute  // diffusion to the attributes

   {  // beginning of the anonymous method

      //We are here in the context of an attribute

      String buffer = "," + Name;

      line = line + buffer

      //access to an embedded variable

    }//end of the anonymous method

      //return to a Class context

   StdOut.write("the ", Name, " class's attributes

                 are ",

                 line, NL);

}

 

 

Example 2

Let's take the previous example and apply the method to the attribute's name directly, in other words, a character String, instead of applying it to the Attribute.

 

Class:printAttribute2()

{

   String line;

   PartAttribute.<Name  // diffusion to the attribute

                             // names

   {

      // this == a character String

      line = line + "," + this;

      // no more need for Name

   }

   StdOut.write("The attributes of the class ", Name,

                " are ",line,NL);

}