banner ads

Instantiating a Class within another Class's Implementation

Instantiating a Class within another Class's Implementation


One class can be instantiated within the implementation of another class. Here the program contains two different classes cls1 and cls2. In the implementation of cls2 we are creating object obj1 ref to cls1 and then calling method of class 1 inside the 2nd class implementation.



REPORT  zsr_test NO STANDARD PAGE HEADING.

*----------------------------------------------------------------------*
*       CLASS cls1 DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cls1 DEFINITION.
  PUBLIC SECTION.
    DATA v_cls1 TYPE char40 VALUE 'Class one data'.
    METHODS m_cls1.
ENDCLASS.                    "cls1 DEFINITION

*----------------------------------------------------------------------*
*       CLASS cls2 DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cls2 DEFINITION.
  PUBLIC SECTION.
    DATA v_cls2 TYPE char40 VALUE 'Class two data'.
    METHODS m_cls2.
ENDCLASS.                    "cls2 DEFINITION

*----------------------------------------------------------------------*
*       CLASS cls1 IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cls1 IMPLEMENTATION.
  METHOD m_cls1.
    WRITE: / v_cls1.
  ENDMETHOD.                                                "m_cls1
ENDCLASS.                    "cls1 IMPLEMENTATION

*----------------------------------------------------------------------*
*       CLASS cls2 IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cls2 IMPLEMENTATION.
  METHOD m_cls2.
    DATA obj1 TYPE REF TO cls1.
    CREATE OBJECT obj1.
    CALL METHOD obj1->m_cls1.
    WRITE: / v_cls2.
  ENDMETHOD.                                                "m_cls2
ENDCLASS.                    "cls2 IMPLEMENTATION

DATA obj2 TYPE REF TO cls2.

START-OF-SELECTION.  CREATE OBJECT: obj2.
  CALL METHOD obj2->m_cls2.


Now at debugging level we see at first the system will call the m_cls2 method. It holds the value of v_cls2 inside m_cls2.


After creation of the object of class cls1 the system gets access to call its method. Now it will call the method m_cls1 and the control will go to inside the class cls1.

 

After completing this method it will again go back to the second method m_cls2. The system will finish the rest of the work there.

 

The output is as follows:

No comments