Methods and constructors


Methods all follow the same syntax rules (see the description of the METHOD instruction, elsewhere), and are usually invoked in context of an existing object. A special kind of method, called a constructor method, is used to actually create an object.

Constructor methods always have the same name as the class in which they are found, and construct an object of that class. There will always be at least one constructor if objects are to be created (NetRexx will add a default constructor that takes no arguments if none are provided). All constructors follow the following rules:

  1. Constructors must call a constructor of their superclass before they carry out any initialization of their own (this is so any initialization carried out by the superclass takes place at the appropriate moment). Therefore the first instruction in a constructor must be either a call to super() (with optional arguments), or a call to this() (with optional arguments). In the latter case, another constructor in the same class is called; eventually one that explicitly calls super() will be invoked and the chain of local constructor calls ends.

    As a convenience, NetRexx will add a default call to super() if the first instruction in a constructor is not a call to this() or super().

  2. By definition, constructors create an object of the current class and return it. Therefore, the RETURNS keyword on the method instruction is optional (if specified, the RETURNS type must match the class), and the only possible forms of the RETURN instruction on a constructor are either 'return this' or 'return' -- in the latter case, the 'this' is assumed (this form will be assumed at the end of a method, as usual, if necessary).

Here is an example of a class with two constructors, showing the use of this() and super(), and taking advantage of the assumptions:

  class MyChars

properties private value=char[] -- the data 'in' the object

method MyChars(c=char[]) -- construct the object from a char array super() -- initialize superclass (in this case Object) value=c -- record the value (without copying)

method MyChars(s=String) -- construct the object from a String this(s.toCharArray()) -- convert to char[] and use the above

Objects of type 'MyChars' could then be created thus:

  myvar=MyChars("From a string")

or by using an argument that has type char[]. Note that all references to constructors must be identified by the use of parentheses, to distinguish them from references to the type (class) of the same name.


[ previous section | contents | next section ]

From 'netrexx.doc', version 1.00.
Copyright(c) IBM Corporation, 1996, 1997. All rights reserved. ©