banner ads

Instance Method vs Static Method

Instance method can access both – instance components as well as static components. Static method can only access static components. In the following example we have instance component v_var and static component cl_v_var. We have an instance method m_one and a static method cl_m_one. We can access both of those components from the instance method but when we want to access instance component from the static method then it will give a syntax error as follows.


REPORT  zsr_test NO STANDARD PAGE HEADING.

*----------------------------------------------------------------------*
*       CLASS cl_one DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_one DEFINITION.
  PUBLIC SECTION.
    DATA v_var TYPE char40 VALUE 'Instance Component'.
    CLASS-DATA cl_v_var TYPE char40 VALUE 'Static Component'.

    METHODS m_one.
    CLASS-METHODS cl_m_one.
ENDCLASS.                    "cl_one DEFINITION

*----------------------------------------------------------------------*
*       CLASS cl_one IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_one IMPLEMENTATION.
  METHOD m_one.
    WRITE: / v_var,
           / cl_v_var.
  ENDMETHOD.                    "m_one

  METHOD cl_m_one.
    WRITE: / cl_v_var.
  ENDMETHOD.                    "cl_m_one
ENDCLASS.                    "cl_one IMPLEMENTATION

START-OF-SELECTION.  CALL METHOD cl_one=>cl_m_one.
  SKIP.

  DATA obj TYPE REF TO cl_one.
  CREATE OBJECT obj.
  CALL METHOD obj->m_one.

The program generates the following output.

No comments