Skip to content

SpecificationIX · Objects

9.2

Methods and This

A method is a subprogram that lives inside a class and works on a particular object: the one named before the dot.

Markdown version

9.2.1 How to write it

⟦Public | Private⟧ Method «nombre»(«parámetros») ⟦As «tipo»⟧
  «instrucciones»
EndMethod

9.2.2 How it works

A method is called on an object: pasos.Sumar(). That object is the receiver, and inside the method it is named with This. To use an attribute or method of the current object, This. is required: a bare name can only be a local variable or a parameter.

ProgramA counter with state

Class Contador
  Private Define valor As Integer;

  Method Constructor(inicial As Integer)
    This.valor <- inicial;
  EndMethod

  Method Sumar()
    This.valor <- This.valor + 1;
  EndMethod

  Method Actual() As Integer
    Return This.valor;
  EndMethod
EndClass

Algorithm Pasos
  Define pasos As Contador <- New Contador(10);
  pasos.Sumar();
  pasos.Sumar();
  Write pasos.Actual();
EndAlgorithm

Output

12

The program finishes normally.

Figure 9.2-1.When calling pasos.Sumar(), This inside the method is the same object as pasos.

The variable pasos and, inside the method, This: both are references pointing to the same object, with valor = 12.

The dot can be chained: New Contador(1).Actual(). An attribute after the dot is a designator; a method call is not. The receiver is computed only once.

There is no overloading: two members of a class cannot share a name, even if one is an attribute and the other a method.

In short

  • A method works on its receiver, the object before the dot.
  • Inside, This. is required for the object's members.
  • Methods can be public or private; there is no overloading.