There are 2 types of constructors in an ABAP CLASS.
- CONSTRUCTOR: The constructor is a method which is used to initialize the class members or assign value to them. It is called once for each instance of an class or more precisely it is called for each object of a class.
- CLASS CONSTRUCTOR: The class constructor is called once for each class irrespective of the number of objects created or instantiated for that class.
Let us look into this concept with the help of an example:
EXAMPLE:
REPORT z_constructor.
*--Class Definition
CLASS l_test DEFINITION.
PUBLIC SECTION.
METHODS: constructor.
CLASS-METHODS: class_constructor.
ENDCLASS.
*--Class Implementation.
CLASS l_test IMPLEMENTATION.
METHOD constructor.
WRITE : / ' inside constructor '.
ENDMETHOD.
METHOD class_constructor.
WRITE : / 'inside class constructor'.
ENDMETHOD.
ENDCLASS.
*--Report.
*--Declare the reference variables.
DATA : ob1 TYPE REF TO l_test,
ob2 TYPE REF TO l_test.
START-OF-SELECTION.
CREATE OBJECT ob1.
CREATE OBJECT ob2.
------------------------------------------------------------------------------------------------------------
OUTPUT:
inside class constructor <-- from class constructor
inside constructor <-- from constructor for object ob1
inside constructor <-- from constructor for object ob2
------------------------------------------------------------------------------------------------------------