Articles > SAP Basis > ABAP Objects > Objects instantiation

Objects instantiation

A class that has been defined and implemented can be used to create objects. This object creation process is called object instantiation. It means that an instance of an object is created based on a class which defines the type of the object. Many objects can be instantiated from one unique class.

Just like any other program data, an object must be referred to by a variable. However, contrarily to what happens with many other data types, this variable is not a container for the object itself but for a reference (pointer) to that object. That’s why the variable is declared with a syntax as follows:

DATA:
  doBP TYPE REF TO LCL_BUSINESS_PARTNER.

This statement declares the variable doBP as a reference to an object of class LCL_BUSINESS_PARTNER. Initially, however this reference is null (its value is {O:INITIAL}) as it doesn’t point to any object. It is normal as the referring variable has been created and the class of the object that will be referred to has been specified but no object has been created.

To actually create an object and assign a reference of that object to variable doBP, the CREATE OBJECT instruction must be used:

  CREATE OBJECT doBP.

The core tasks of this instruction is to allocate memory for the new object, to create an instance of the CLASS which doBP refers and to finally store the address of the allocated memory in variable doBP. We will see in a dedicated article that this instruction also triggers the execution of a special method called the CONSTRUCTOR. However, as we didn’t define such method in our example, no such execution has been performed.

Now that we have built a valid object, we may call its methods so that it provides its expected functionality.

  CALL METHOD doBP->m_SetName EXPORTING Name = 'Partner1'.
  CALL METHOD doBP->m_SetVAT EXPORTING VAT = 'FR123456789'.

This is achieved by calling the methods of the object through its reference variable.


Leave a comment!