Object Oriented ABAP Static Constructor in Local Class

Similar to instance constructor, static constructor is a special method called by the system runtime when the class is accessed for the first time during that program.

How to define static constructor? Static constructor is basically a static method. To define a static constructor, In the ABAP Class definition, create a method with name CLASS_CONSTRUCTOR using statement CLASS-METHODS.

CLASS <class name> DEFINITION.
PUBLIC SECTION.
...
CLASS-METHODS CLASS_CONSTRUCTOR.
ENDCLASS.

CLASS <class name> IMPLEMENTATION.
METHOD CLASS_CONSTRUCTOR.
...
ENDMETHOD.
ENDCLASS.

Few important points related to static constructor:

  • Just like instance constructor, static constructor cannot be called explicitly, but will be called automatically by the runtime environment
  • Static constructors cannot have any parameters or exceptions
  • The static constructor is executed only once per program.
  • Static constructor is defined in the public section of the ABAP class.
  • A class cannot have more than one static constructor

Let’s understand static constructor with the help of an example:

In above example we have defined a static constructor and a static method. Next, we call the static method. The output of the program is:

It indicates that the static constructor is called first, and then the static method. The static constructor is called implicitly. Next, try calling the hello method again. This time, the static constructor will not get called, indicating that the static constructor is called only once.