Skip to content

SpecificationIX · Objects

9.3

Constructors and New

New creates an object and runs its constructor, which prepares the attributes before anyone uses it.

Markdown version

9.3.1 How to write it

Method Constructor(«parámetros»)
  «instrucciones»
EndMethod
New «Clase»(«argumentos»)

9.3.2 How it works

Declaring a class-typed variable creates no object: the variable stays without a value until it is assigned one created with New.

  1. 1A new object is reserved with its attributes without a value.

  2. 2The constructor runs with inicial = 10, and This.valor receives 10.

  3. 3The reference to the object is stored in the variable.

Figure 9.3-1.What happens when New Contador(10) is evaluated.

The variable pasos starts empty. An object with the attribute valor is reserved, the constructor gives it 10 and finally pasos receives the reference to the object.

ProgramA constructor that prepares the object

Class Contador
  Private Define valor As Integer;

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

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

Algorithm Crear
  Write New Contador(10).Actual();
EndAlgorithm

Output

10

The program finishes normally.

If the class inherits, the superclass part is built before the constructor body. When the superclass constructor needs arguments, the first statement must be Super.Constructor(…).

In short

  • New Class(…) creates an object and runs its constructor.
  • There is at most one constructor; without it, an implicit one that initializes nothing.
  • Declaring a class variable does not create the object.
  • The superclass is built first.