The Constructor

The constructor of a class is a collective attribute named new. It must be a function that has no output argument. The constructor is just like a normal function, which makes no mentioning of the class. The result of calling the constructor is the creation of a class member. Any local variable of the constructor whose name matches that of a member attribute of the class, will be assigned to the corresponding attribute of the class member. Any attribute of the member whose name is not a local variable of the constructor will be given the default value.

A very simple and effective way to write a constructor is to write a one-liner function. For example

   student = class
             public name = "xxx xxx";
             public id = "000000";
             public age = 18;
             ...
             new = (name, id, age) -> ();
             end

At first sight, the constructor may appear to be doing nothing at all. Actually, when the constructor is called with three input arguments, a function stack is created which has three local variables named name, id, and age. The values of the three local variables are the arguments passed to the constructor when it's called. Because all these three names are also names of member attributes of the class, a class member is created whose name, id, and age attributes are the input arguments of the constructor.

In this example the constructor simply uses the input arguments as values of member attributes without any checking. If one would like to manually check the validity of the input arguments, one can write some code in the constructor to do so. If the checking fails, error can be generated and new class member is not created. Note that if the definition of each member attribute has a domain, then even if the constructor does no explicit value checking, the domain-checking is still performed. Therefore a simple constructor like the above one may still be sufficient.

In the absence of a constructor, when the class definition is processed the interpreter will generate a default constructor. When the default constructor is called, it will create a member of the class all of whose attributes have default values. Note that the default constructor is equivalent to

         class
             ...
             new = () -> ();
             ...
         end



Subsections
oz 2009-12-22