Using CLASS CONSTRUCTOR in SAP OOABAP

What is a Class Constructor in OOABAP ?, Working with Class Constructor in Object Oriented ABAP Programming

+ -

This is a type of CONSTRUCTOR, this method is executed whenever a first call to the class is made, the call may be through instance or through class name.

These are also called as STATIC CONSTRUCTORS, the name must be CLASS_CONSTRUCTOR.

If you are coming directly for this lesson we highly recommend go through previous lesson Using CONSTRUCTOR method in SAP classes for better understanding.

Example: We will add a class constructor to make default material type as 'FERT'(Finished Product)

Follow the below steps to create a class constructor.

Go to SE24, provide the class name ZCL_SAPN_MATERIALS, click on change.

Go to attributes tab and add an attribute to make default material type.

Using Class Constructor method in SAP Classes

Go to methods and add a method name CLASS_CONSTRUCTOR as below.

Using Class Constructor method in SAP Classes

We can not add any exporting and importing parameters to a CLASS_CONSTRUCTOR method.

Double click on the method CLASS_CONSTRUCTOR and add below code.

Using Class Constructor method in SAP Classes

 METHOD CLASS_CONSTRUCTOR.
*Set default material type as FERT
 MAT_TYPE = 'FERT'. 
ENDMETHOD.
Here we take a small example to test this one.The below on is a simple example and explains you a lot.
REPORT ZSAPN_CLASS_CONSTRUCTOR.
DATA : LO_MATERIAL TYPE REF TO ZCL_SAPN_MATERIALS. "Declare class 

CREATE OBJECT LO_MATERIAL "create object CONSTRUCTOR method will trigger
  EXPORTING
    IM_SPRAS = 'E'.
**When ever first call to a class is made class constructor will trigger
WRITE:/ 'Executed through class constructor', ZCL_SAPN_MATERIALS=>MAT_TYPE. "Executed through Class Constructor

WRITE:/ 'Executed through Constructor', LO_MATERIAL->LANGUAGE . "Executed through constructor method

If we have both CONSTRUCTOR and CLASS_CONSTRUCTOR in our class, upon a class call which will trigger first.....First CLASS_CONSTRUCTOR will be triggered.

Learner Questions


No Questions by learners, be first one to ask ..!!

    Please Sign in to ask a question

    Was this lesson helpful to you? Yes No 42 People out of 45 think this lesson helpful


    Lesson Navigation

    ←Previous Chapter
    Next Lesson → Interfaces in SAP OOABAP