Contents

The new and init methods.

Special methods

There are two special methods, which are used to initialize a class and its objects.

The init() method

The init method is used to initialize a class, and in particular to initialize the values of any static variables. It is called automatically the first time that one of the class’s (static) fields is accessed, or when an instance of the class is created.

Some other points to note about init :-

The new() method

The new method is used to initialize an object, ie an instance of a particular class. The method is not invoked explicitly however. Rather, in order to create an instance the class name is used like a function call, and the new() method is invoked automatically. So for example :-

import io

class X()
   public new(a, b)
      write("in new a=", a, " b=", b)
      return
   end
end

procedure main()
   local i
   i := X(3, 4)
end

This writes "in new a=3 b=4".

Some other points to note about new() :-

Class.create_instance()

It is sometimes desirable to provide a way of creating a new instance which bypasses the new() method. The method lang.Class.create_instance() provides a way to do this. It can be called from within a class, and it returns a new instance of that class. new() is not invoked, and all of the instance variables are set to &null. It is the responsibility of the caller to initialize the instance as appropriate.

Another method, lang.Class.create_raw_instance(), is just like create_instance(), except that the new object is in an even more primitive state, which allows const fields to be assigned and new to be invoked. The method lang.Class.complete_raw_instance() must be used to complete the object’s initialization.

Here is an example illustrating the use of create_instance().

Download createinstance.icn

import io, lang

class X()
   private x

   public static f(x)
      local i
      write("In X.f()")
      i := Class.create_instance()
      i.x := 2 * x
      return i
   end

   public new(x)
      write("In X.new()")
      self.x := 3 * x
      return
   end
end

procedure main()
   write(to_string(X(123)))
   write(to_string(X.f(345)))
end

The output is :-

In X.new()
object X#1(x=369)
In X.f()
object X#2(x=690)
Contents