[top] [up] [next]

Sending messages to instances


After an instance has been created it is possible to send messages to it, i.e. calling methods of the class., The operator <-/2 is used to send a message to an instance or to a set of instances. The left operand must be an instance or a goal to find instances that match and the right operand is the name of a method possibly with arguments (if the method requires arguments). Below there are several examples of creating a new instance of the class stack and sending the init message to it.

    X new_obj stack, X<-init. %Sets the attributes of X to default values
    X new_obj stack, X<-init([a], 1). %Initializes the stack with 1 element

If the two examples above were executed after each other two separate instances of the class were created, the current module would contain the following stack instances.

    stack([], 0).
    stack([a], 1).

It is possible to send the same message to each instance of a class, the left operand of the <-/2 operator must then be a goal for finding a match, for instance:

    stack(L, V)<-push(b).

Each of the two class instances match with 'stack(L, V)' and so the message 'push' is send to each instance. To send a message to an empty stack instance the goal would be 'stack([], 0)<-push(b).'.

Sending messages to a superclass

Sometimes it is necessary to explicitly call a method of a superclass. This can be done by using either the ::<-/1 or the ::<-/2 operator. Both these operators cannot be used to send messages to other instances and they may only be used inside the implementation of a class method. This is so because both these operators send a message to 'this' instance.

    class test1.  %Declare a super class for the class 'test2'
      public.
        match/2.
      private.
        match2/2.
    endclass test1.

    test1::match(Y, a).
    test1::match2(Y, b).

    %----------------------------------
    class test2.
        inherit test1.
      public.
        match/2.    %Overload the 'match/2' method
        call3/1.
        call4/1.
      private.
        match2/2.  %Overload the 'match2/2' method
    endclass test2.

    test2::match(Y, c).
    test2::match2(Y, d).

    test2::call3(S) :-
        ::<-match(S, S).  %Call a method of a superclass

    test2::call4(S) :-
        test1::<-match2(S, S).  %Call a method of the superclass 'test1'

In the example above the method 'call4' of the class 'test2' attempts to call the method 'match2' of the class 'test1', this call will always fail because 'match2' is declared as a private method by the class 'test1'. Private methods are no accessible by other classes.

[top] [up] [next]

 

info@trinc-prolog.com