Preferred Parameter in a Method
Preferred parameter is used when we have more than one optional parameter. In this case we can declare the values to the parameters. But if we don’t mention the parameter then preferred parameter always populates the declared value.
In the following example we have a method with optional parameters v_opt & v_pre. We have mentioned that v_pre is the preferred parameter. Now at the calling of the method we are passing values to the parameters. At the first call we pass values to the mentioned parameters. So the system will easily recognize the variable’s values. But in the second call we haven’t mentioned the parameter. Since v_pre is the preferred parameter, it will populate with the declared values.
REPORT zsr_test NO STANDARD PAGE HEADING.
*----------------------------------------------------------------------*
* CLASS cl_pr_para DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_pr_para DEFINITION.
PUBLIC SECTION.
METHODS m_pr_para IMPORTING v_opt TYPE i OPTIONAL
v_pre TYPE i OPTIONAL
PREFERRED PARAMETER v_pre.
ENDCLASS. "cl_pr_para DEFINITION
*----------------------------------------------------------------------*
* CLASS cl_pr_para IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_pr_para IMPLEMENTATION.
METHOD m_pr_para.
WRITE: / 'Optional Parameter =', v_opt,
/ 'Preferred Parameter =', v_pre.
ENDMETHOD. "m_pr_para
ENDCLASS. "cl_pr_para IMPLEMENTATION
START-OF-SELECTION. DATA obj TYPE REF TO cl_pr_para.
CREATE OBJECT obj.
CALL METHOD obj->m_pr_para( v_opt = 10
v_pre = 12 ).
SKIP.
CALL METHOD obj->m_pr_para( 15 ).
*----------------------------------------------------------------------*
* CLASS cl_pr_para DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_pr_para DEFINITION.
PUBLIC SECTION.
METHODS m_pr_para IMPORTING v_opt TYPE i OPTIONAL
v_pre TYPE i OPTIONAL
PREFERRED PARAMETER v_pre.
ENDCLASS. "cl_pr_para DEFINITION
*----------------------------------------------------------------------*
* CLASS cl_pr_para IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_pr_para IMPLEMENTATION.
METHOD m_pr_para.
WRITE: / 'Optional Parameter =', v_opt,
/ 'Preferred Parameter =', v_pre.
ENDMETHOD. "m_pr_para
ENDCLASS. "cl_pr_para IMPLEMENTATION
START-OF-SELECTION. DATA obj TYPE REF TO cl_pr_para.
CREATE OBJECT obj.
CALL METHOD obj->m_pr_para( v_opt = 10
v_pre = 12 ).
SKIP.
CALL METHOD obj->m_pr_para( 15 ).
We have the following output of this program.
Post a Comment