Summary -

In this topic, we described about the below sections -

Constructors are special methods that are called automatically while creating an object or instantiated (accessing the class components) first time. Constructor gets triggered when an object is created.

To trigger a method, we need to call a method. CONSTRUCTORS are two types and those are -

Constuctor Types Description
Instance constructor Instance constructor methods can only have importing parameters and there will not be any exporting parameters.
The name of the CONSTRUCTOR method must be CONSTRUCTOR only.
Static constructor Static constructors are mainly used to set the default values globally irrespective of instances/methods. These methods will not have any importing and exporting parameters. Static constructor methods gets executed only once.
The name of the CLASS CONSTRUCTOR must be CLASS_CONSTRUCTOR.

Example -

Simple example to explain how the constructor is being triggered.


Code -

*&---------------------------------------------------------------------*
*& Report  Z_CONSTRUCTORS
*&---------------------------------------------------------------------*
*& Written by TutorialsCampus
*&---------------------------------------------------------------------*

REPORT  Z_CONSTRUCTORS.

* Class & methods definition
CLASS classnew DEFINITION.
PUBLIC SECTION.

* Instance constructor definition
  METHODS constructor.

* Static constructor definition
  CLASS-METHODS class_constructor.
ENDCLASS.

* Class & method implementation
CLASS classnew IMPLEMENTATION.

* Instance method implementation
  METHOD constructor.
     WRITE:/ 'Instance Constructor Triggered'.
  ENDMETHOD.

* Static method implementation
  METHOD class_constructor.
     WRITE:/ 'Static Constructor Triggered'.
  ENDMETHOD.
ENDCLASS.


START-OF-SELECTION.

* Defining object objectnew for the class classnew
DATA: objectnew TYPE REF TO classnew.

* Creating object objectnew 
CREATE OBJECT objectnew.


Output -

Class Constructors Example Output

Explaining Example -

In the above example, each and every statement is preceeded with a comment to explain about the statement. Go through them to get clear understanding of example code.

constructor is instance constructor as it was defined by using METHODS clause. class_constructor is static constructor as it was created by using CLASS-METHODS clause.

The static and instance constructors are called when the object objectnew is created. Static constructor is the first constructor triggered before and instance constructor triggered.