Using CLASS-CONSTRUCTOR in SAP Local classes

Using CLASS-CONSTRUCTOR in SAP Local Classes, Object Oriented ABAP Constructor method.

+ -

CLASS-CONSTRUCTOR is a special type of method which will execute automatically when the first call of a class is made (call may through instance or through method).

CLASS-CONSTRUCTOR dosen`t support any importing and exporting parameters, it is mainly used to set default values in classes.

Please refer previous lesson Using CONSTRUCTOR method in SAP Local classes .

Program for CLASS-CONSTRUCTOR


REPORT ZSAPN_LOCAL_CLASS_CONSTRUCTOR.
CLASS CL_CONSTRUCTOR_EXAMPLE DEFINITION DEFERRED . "class is defined in next lines
DATA LO_CLASS TYPE REF TO CL_CONSTRUCTOR_EXAMPLE. "declare class
DATA : WA_MAKT TYPE MAKT. "makt work area
DATA : LV_DATE TYPE SY-DATUM. "declare date
PARAMETERS : P_MATNR TYPE MARA-MATNR. "input material number
PARAMETERS P_SPRAS TYPE MAKT-SPRAS. "input language to pass to constructor


CLASS CL_CONSTRUCTOR_EXAMPLE DEFINITION. "class definition
  PUBLIC SECTION.
    DATA : LV_LANGUAGE TYPE SPRAS.
    METHODS : CONSTRUCTOR "Constructor method
              IMPORTING IM_SPRAS TYPE SPRAS.
    CLASS-METHODS : CLASS_CONSTRUCTOR ."Class Constructor method .
    METHODS : GET_MATERIAL_DESCRIPTIONS "method to get material descriptions
              IMPORTING IM_MATNR TYPE MARA-MATNR
              EXPORTING EX_MAKT TYPE MAKT.

ENDCLASS.

START-OF-SELECTION.
  CREATE OBJECT LO_CLASS "create object for class, constructor method will trigger here
    EXPORTING
      IM_SPRAS = P_SPRAS.

  CALL METHOD LO_CLASS->GET_MATERIAL_DESCRIPTIONS "call method to get materiald escriptions
    EXPORTING
      IM_MATNR = P_MATNR
    IMPORTING
      EX_MAKT  = WA_MAKT.


  WRITE :/ WA_MAKT-MATNR, WA_MAKT-MAKTX, WA_MAKT-SPRAS. "print data
  WRITE:/ 'Generated at :', LV_DATE .
CLASS CL_CONSTRUCTOR_EXAMPLE IMPLEMENTATION. "class implementation
  METHOD: CONSTRUCTOR.
    LV_LANGUAGE = IM_SPRAS.
  ENDMETHOD.
  METHOD : CLASS_CONSTRUCTOR.
    LV_DATE = SY-DATUM . "add date using class constructor
  ENDMETHOD.
  METHOD: GET_MATERIAL_DESCRIPTIONS.
    SELECT * FROM MAKT INTO EX_MAKT
      WHERE MATNR = IM_MATNR AND SPRAS = LV_LANGUAGE .
    ENDSELECT.
  ENDMETHOD.
ENDCLASS.               "CL_CONSTRUCTOR_EXAMPLE

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 10 People out of 10 think this lesson helpful


    Lesson Navigation

    ←Previous Chapter
    Next Lesson → Interfaces in local classes in SAP OOABAP