Friday, January 10, 2014

Object Oriented ABAP Tutorials-5 Working with Methods

OOABAP Tutorials - Working with Methods
Object Oriented ABAP (OOABAP) Tutorials-5 Working with Methods. Welcome to sap abap interview questions. 

In this post of SAP OOABAP Tutorials with Examples - you will learn about Methods in OOABAP and how to work with methods and what is the functionality of methods in Object Oriented ABAP. This is the fifth post in the series of OOABAP tutorials with examples.



ABAP OO Tutorials with Examples


Before going to read this article, sapabapiq.com suggest you to read previous articles on OOABAP tutorials to better understand.
















Methods and its functionality in OOABAP




1.1    Method with one import parameter/ only one non-optional parameter



Theme


This program will demonstrate different ways of calling a method which has   only one import parameter.

This strategy is also valid for cases where a method has more than one import parameters,  but only one of them being non-optional.




Program


This program has a class , C1 with a method : meth1. This method has only one import parameter(input1). Look at the method implementation for details. 


The main purpose of this program is to demonstrate the different ways of calling a method with single import parameter.





Code Dump


REPORT YSUBDEL .

 CLASS C1 DEFINITION.
  PUBLIC SECTION.
   DATA : NUM TYPE I VALUE 5.
   METHODS : METH1 IMPORTING INPUT1 TYPE I   .
 ENDCLASS.

 CLASS C1 IMPLEMENTATION.
  METHOD : METH1.
   num = NUM * INPUT1 .
   WRITE:/5 NUM .
   num = 5.
  ENDMETHOD.
 ENDCLASS.


 START-OF-SELECTION.
  DATA : OREF1 TYPE REF TO C1.
  CREATE OBJECT : OREF1.
* Different ways of calling the method with one import parameter
   CALL METHOD OREF1->METH1 EXPORTING INPUT1 = 4.
   CALL METHOD OREF1->METH1( INPUT1 = 5 ).
   CALL METHOD OREF1->METH1( 6 ).




Output


20
25
30






1.2    Import parameters passed by ref. can’t be changed inside the method .







Theme


Parameters can be passed to a method as import parameters in two fashion:-

By reference
By value.

Parameters passed by value can be changed internally in a method. But, parameters passed by reference cannot be changed in the method.





Program description


This program contains a class C1 with a method METH1. This method contains two input parameters :  -

INPUT1  : passed by reference
INPUT2 : passed by value.

 The method METH1 attempts to change INPUT1. On compilation, an error is displayed.  This establishes that input parameters passed by reference cannot be changed within the method.












Dump

REPORT YSUBDEL .

 DATA : num TYPE I.
 CLASS C1 DEFINITION.
  PUBLIC SECTION.
   METHODS : METH1 IMPORTING INPUT1 TYPE I
                             value(input2) type i.
 ENDCLASS.

 CLASS C1 IMPLEMENTATION.
  METHOD : METH1.
   Input1 = 4.
   write:/5 input1.
  ENDMETHOD.
 ENDCLASS.


 START-OF-SELECTION.
  DATA : OREF1 TYPE REF TO C1.
  CREATE OBJECT : OREF1.
   num = 3.
   CALL METHOD OREF1->METH1 EXPORTING INPUT1 = 4
                                      input2 = num.





Output


On compilation, an error message is generated.

Now, instead of changing input1, change the import parameter input2 (passed by value)within the method. 

The program will get successfully compiled and executed.








1.3    Use of PREFERRED PARAMETER in a method




Theme


If there are more than one OPTIONAL import parameters in a method and no non-optional import parameters without values, one can type in the clause PREFERRED PARAMETER after the list of import parameters to specify which of the optional parameters will get more preference compared to others when the method will be called using syntax :- CALL METHOD objref->meth(<val>).


In other words, it decides which of the optional parameters will be assigned the value ‘VAL’.





Program Description


This program contains a class C1 containing method METH1 which has two optional parameters , INPUT1 and INPUT2. Out of them, parameter INPUT2 is declared as preferred parameter. The method simply displays the value of two import parameters .

Notice the last line of the program and see the output.

The output will establish that the preferred parameter INPUT2 gets the value passed to the method when it is called using the syntax:-

CALL METHOD objref->meth(<val>).







Dump
REPORT YSUBDEL .

 CLASS C1 DEFINITION.
  PUBLIC SECTION.
   METHODS : METH1 IMPORTING INPUT1 TYPE I optional
                             input2 TYPE I OPTIONAL
                             PREFERRED PARAMETER INPUT2.
 ENDCLASS.

 CLASS C1 IMPLEMENTATION.
  METHOD : METH1.
   write:/5 input1 ,
         /5 input2 .
  ENDMETHOD.
 ENDCLASS.


 START-OF-SELECTION.
  DATA : OREF1 TYPE REF TO C1.
  CREATE OBJECT : OREF1.
   CALL METHOD : OREF1->METH1( input1 = 5  input2 = 3 ).
   skip 2.
   write:/5 'Next call'.
   call method oref1->meth1( 10 ) .

Output
         5 
         3 
           
           
Next call  
         0 
        10

 






1.4    Use of EXPORT and CHANGING parameters of a method



Theme



This program will demonstrate the use of EXPORTING and CHANGING parameters of a method.





Program description


The program contains a method TAX_CALC belonging to the class CTAX. It receives GRADE as IMPORTING parameter and SALARY as CHANGING parameter. 

Based on the grade, the EXPORTING parameter ITAX is calculated and the CHANGING parameter , SALARY is modified by deducting tax from it.




REPORT YSUBDEL .

DATA : w_tax    type p decimals 2 ,
       w_salary type p decimals 2 .

 CLASS CTAX DEFINITION.
  PUBLIC SECTION.
   METHODS : TAX_CALC IMPORTING grade  TYPE C
                      EXPORTING itax   TYPE P
                      CHANGING  salary TYPE P .
 ENDCLASS.

 CLASS CTAX IMPLEMENTATION.
  METHOD : TAX_CALC.
   CASE grade.
    WHEN 'A01'.
     itax = salary * '0.2'.
    WHEN 'A02'.
     itax = salary * '0.1'.
    WHEN OTHERS.
     itax = salary * '0.15'.
   ENDCASE.
    salary = salary - itax.
  ENDMETHOD.
 ENDCLASS.


 START-OF-SELECTION.
  DATA : OREF1 TYPE REF TO CTAX.
  CREATE OBJECT : OREF1.
  w_salary = 30000.
  w_tax    = 0    .
  write:/5 'Before method call, salary and tax are' ,
           w_salary ,
           w_tax .
   CALL METHOD OREF1->TAX_CALC EXPORTING grade = 'A01'
                               IMPORTING itax  = w_tax
                               CHANGING salary = w_salary.
    write:/5 'After method call, salary and tax are' ,
           w_salary ,
           w_tax .



Output


Before method call, salary and tax are        30,000.00              0.00  

 After method call, salary and tax are 
       24,000.00          6,000.00   





1.5    Method using Internal Table as one of the parameters



Theme


This program demonstrates how an internal table can be used as one of the interface parameters of a method.



Program Description

The program contains a method : GETMARA in class : GET_MATERIALS

 It accepts material group, MATGR as import parameter and details out the details of the materials belonging to that material group into I_TAB , which is an internal table used as EXPORTING parameter for the method.




REPORT  YSUBOOPS5    .

types : begin of typ_tab ,
             matnr like mara-matnr ,
             meins like mara-meins ,
       end of typ_tab .

  data : itab type standard table of typ_tab ,
         x_tab LIKE LINE OF ITAB.

 CLASS get_materials DEFINITION.
 PUBLIC SECTION.
 METHODS : getmara IMPORTING matgr TYPE C
                   EXPORTING l_tab TYPE ANY TABLE.
 endclass.

 CLASS get_materials IMPLEMENTATION.
  METHOD : getmara .
   SELECT matnr meins INTO TABLE l_tab
   FROM MARA
   WHERE MATKL = matgr.
  ENDMETHOD.
 ENDCLASS.

 PARAMETERS : p_matkl like mara-matkl .

 START-OF-SELECTION.
 DATA : w_mat TYPE REF TO get_materials.
 CREATE OBJECT : w_mat.
 CALL METHOD w_mat->getmara EXPORTING matgr = p_matkl
                            IMPORTING l_tab = itab .
 LOOP AT ITAB INTO X_TAB.
  WRITE:/5 X_TAB-MATNR , X_TAB-MEINS.
 ENDLOOP.



Output



One/more than one records with material number and basic unit, depending on the material group entered in the selection-screen.




1.6    Use of RETURNING parameters in method





Theme


To get some values from a method , one can use the EXPORTING, CHANGING or RETURNING parameters.

If one uses RETURNING parameters, the following restrictions apply:-


(1) No EXPORTING/CHANGING parameters can be used for the method.


(2) Only one RETURNING parameter can be used.

(3) RETURNING parameters are only passed by value.

This program demonstrates the use of RETURNING parameters and the various ways   to call a method with RETURNING parameter to get the value into some variable.




Program Description

Method M1 in class C1 have two input parameters(INPUT1 and INPUT2), which are used to derive value for RETURNING parameter , RESULT.

The program demonstrates various syntaxes that can be used to call a method of this kind.



Report ysubdel1 message-id 00.

data : w_num type i.

class c1 definition .
 public section.
   methods : m1 importing input1        type i
                          input2        type i
                returning value(result) type i .
endclass.

class c1 implementation.
 method  : m1.
  result = input1 * 2 + input2.
 endmethod.
endclass.

 start-of-selection.
 data : obj1 type ref to c1 .
   create object obj1.
* Syntax 1  
   call method obj1->m1 EXPORTING input1 = 5
                                  input2 = 4
                        RECEIVING result = w_num.
   write:/5 w_num .
* Syntax 2  
   w_num = obj1->m1( input1 = 10 input2 = 20 ).
   write:/5 w_num .
* Syntax 3  
   move obj1->m1( input1 = 2 input2 = 3 ) to w_num .
   write:/5 w_num .



Output


14
40
7




1.7    Demo on Static Method



Theme


This program will show how to declare and define a static method and how it can be called using class component selector.



In the following program, method : TESTMETHOD is defined as static method and is called later using class component selector, ‘=>’.










Dump

REPORT  YSUBOOPS19                              .

data : num type i.

class testclass definition.
 public section.
  class-methods : testmethod.
endclass.

class testclass implementation.
 method : testmethod.
  num = 5.
  write:/5 num.
endmethod.
endclass.

start-of-selection.
 call method testclass=>testmethod.


Output
5




1.8    Static methods can only use static attributes, instance methods use both


Theme

Static methods of a class can only use static attributes of that class. It cannot use instance attributes. But, instance methods can use both.






Program Description
The following program contains a class C1 which contains the following:-
Component
Type
Static/Instance
stnum
Data
static
Instnum
Data
Instance
Stmeth
Method
Static
Instmeth
Method
Instance

Both the static and instance methods are attempting to display values of the static and instance attributes: STNUM and INSTNUM .

On compilation, an error will be generated which will demonstrate that static method STMETH cannot work with instance attribute, INSTNUM.











Dump
REPORT YSUBDEL.

CLASS C1 DEFINITION.
PUBLIC SECTION.
 CLASS-DATA : STNUM TYPE I VALUE 5.
 DATA : INSTNUM TYPE I VALUE 6 .
 CLASS-METHODS : STMETH .
 METHODS : INSTMETH .
ENDCLASS.

CLASS C1 IMPLEMENTATION.
  METHOD : STMETH .
   WRITE:/5 STNUM .
   WRITE:/5 INSTNUM .
  ENDMETHOD.
 
  METHOD INSTMETH.
   WRITE:/5 STNUM .
   WRITE:/5 INSTNUM .
  ENDMETHOD.
 ENDCLASS.

 START-OF-SELECTION.
  DATA : OREF1 TYPE REF TO C1.
  CALL METHOD c1=>stmeth .
  CREATE OBJECT OREF1.
  CALL METHOD oref1->instmeth.



Output
On compilation,you get the error:-

Remove the line in bold in the program and compile. It will get successfully compiled and executed.




1.9    Method Raising Exceptions



Theme


Methods can raise exceptions like function modules which can be handled after calling the method, depending on various sy-subrc values. This program will demonstrate that.











Program description

The program provides the user a selection-screen where the user enters a numeric value. If the user entry is <5, he gets an information message ‘Should be >=5’. Else, five times of the value entered is displayed by the program on execution.

The class C1 in this program contains method M1 which imports value for NUM1 , and returns five times of it through the export parameter, NUM2.
However, if the value passed to NUM1 is lesser than 5, it raises an exception E1 with some error message.

The method M1 is called after creating an object from the class. User-entered value in the parameter field : P_NO  is passed to importing parameter NUM1.












Dump

report ysubdel1 message-id 00.

class c1 definition .
 public section.
  methods : m1 importing num1 type i
               exporting num2 type i
            exceptions e1.
endclass.

class c1 implementation.
 method  : m1.
  if num1 lt 5 .
   message i398(00) with 'Should be >=5' raising e1.
  else .
   num2 = num1 * 5 .
  endif.
 endmethod.
endclass.

  parameters : p_no type i .

  start-of-selection.
   data : obj1 type ref to c1 .
   create object obj1.
   call method obj1->m1 exporting num1 = p_no
                        importing num2 = p_no
                        exceptions e1 = 1.

  IF sy-subrc <> 0.
  MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
          WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
  ELSE.
   write:/5 p_no .
  ENDIF.



Output

The program provides the user a selection-screen where the user enters a numeric value. 

If the user entry is <5, he gets an information message ‘Should be >=5’. Else, five times of the value entered is displayed by the program on execution.




1.10  Method can call itself


Theme

Method of a class can call itself .But, please do not forget to specify some exit point to the method. Else, it will create an infinite loop.


Program Description

The program following contains a method M1 in a class C1. It increases the value of static variable, STATNUM by 10 and displays it.Then, if the value of STATNUM is <=100 , it calls itself again.











Dump
report ysubdel1 message-id 00.

class c1 definition .
 public section.
 class-data : statnum type i .
  methods : m1 .
endclass.

class c1 implementation.
 method  : m1.
   statnum = statnum + 10.
   if statnum gt 100.
    exit.
   endif.
   write:/5 statnum .
   call method m1.
 endmethod.
endclass.

    start-of-selection.
   data : obj1 type ref to c1 .
   create object obj1.
   call method obj1->m1 .

Output
10
20
….
100




1.11  Use of ME in methods



Theme


A method can have a variable defined within it having the same name as one of the attributes of the class to which the method belongs to.

To clearly identify the class level attribute, the selector ME is used.



Program Description


Class TESTCLASS contains method TESTMETHOD. There is a variable I_NUM declared as public attribute in the class as well as in the implementation part of the method.

To access the variable I_NUM at the class level within the method, the selector ME is used. Please see the ouputs of this program for better understanding.











Dump
REPORT  YSUBOOPS17


class testclass definition.
 public section.
  data : i_num type i value 5.
  methods : testmethod .
endclass.

class testclass implementation.
 method :testmethod.
  data : i_num type i value 2.
   write:/5 me->i_num ,   " access variable of the class
         /5     i_num .   " access variable of the method
 endmethod.

 endclass.

 start-of-selection.
 data : i_num type i.
  data : my_obj type ref to testclass.
  create object : my_obj.
  call method my_obj->testmethod.

Output
5
2



1.12  Pointer Tables



Theme



This program will demonstrate the use of pointer tables

Program Description




The program below uses pointer table : MYOBJ_TAB.









Code
REPORT  YSUBOOPS19                              .

class testclass definition.
 public section.
  methods : testmethod .
  class-data : num type i.
endclass.

class testclass implementation.
 method : testmethod.
  num = num + 5.
  write:/5 num.
 endmethod.
endclass.

start-of-selection.
data : myobj type ref to testclass ,
       myobj_tab type table of ref to testclass.

do 5 times.
 create object myobj .
 append myobj to myobj_tab.
enddo.

 loop at myobj_tab into myobj.
   call method : myobj->testmethod.
 endloop.


Output
5
10
15
20
25




1.13  Dynamic Method Calls





Theme
One can call methods dynamically. Following restrictions apply:-

*  Name of the method can be dynamic for static/instance method.

*  Name of the class while calling static method can be dynamic.

*  Both the name of the static method and the class containing it can be dynamic.

While doing so, it is better to use uppercase to assign the name of the class/methods to the variables( which will be used for dynamic assignment)




Program Description


The following program contains class C1 with static method(STATM) and dynamic method(INSTM). The program utilizes all the syntaxes to call these static/instance methods dynamically.














Dump

REPORT  YSUBOOPS19         .

 data : f(6)   type c      ,
        g(10)  type c      .

class c1 definition.
public section.
  class-methods : statm .
  methods : instm .
endclass.

class c1 implementation.
 method : statm .
  write:/5 'I am static method'.
 endmethod.

 method : instm.
  write:/5 'I am instant method'.
 endmethod.
endclass.


start-of-selection.
 data : oref type ref to c1.
  create object oref.
* Name of instance method can be dynamic 
  f = 'INSTM'.   call method oref->(f).
* Name of static method can be dynamic  
   f = 'STATM'.  call method oref->(f).
* Name of the class can be dynamic for static method call  
  f = 'C1'.      call method (f)=>statm.
* Name of the method can be dynamic for static method call 
  f = 'STATM'.   call method c1=>(f).
* Both can be dynamic for static method call 
   g = 'C1'.     call method (g)=>(f).




Output

I am instant method
 I am static method 
 I am static method 
 I am static method 
 I am static method 





1.14  Use of parameter table




Theme

For dynamic method call, one can use the concept of PARAMETER TABLE to include references of all interface parameters of the method(instead of mentioning them separately).




Program
Description

The program contains class C1 with a method M1. This method has one IMPORTING parameter , ‘P1’ and one EXPORTING parameter ‘P3’.

P3 is calculated within the method .
Here, parameter table PTAB is used to dynamically call the method M1 .

Please note that, parameter tables work only when a method is called dynamically(i.e. to day, the name of the method/class is determined at runtime).


Dump
REPORT  YSUBOOPS24  .

DATA : i_result type i,
       i_num    type i value 5 .
DATA   f(2)     TYPE c VALUE 'M1'.

 CLASS cl_abap_objectdescr DEFINITION LOAD .

DEFINE : poptable.
  ptab_line-name = &1.
   ptab_line-kind = CL_ABAP_OBJECTDESCR=>&2.
  GET REFERENCE OF &3 INTO  ptab_line-value.
  INSERT ptab_line INTO TABLE ptab.
  IF sy-subrc ne 0.
    EXIT.
  ENDIF.
 END-OF-DEFINITION.

CLASS c1 DEFINITION.
  PUBLIC SECTION.
  METHODS m1 IMPORTING p1 TYPE i
             exporting p3 type i .
ENDCLASS.

CLASS c1 IMPLEMENTATION.
  METHOD m1.
    p3 = p1 + 200.
  ENDMETHOD.
ENDCLASS.

DATA r TYPE REF TO c1.
DATA: ptab TYPE abap_parmbind_tab,
      ptab_line LIKE LINE OF ptab.

START-OF-SELECTION.

 poptable : 'P1' EXPORTING i_num ,
            'P3' IMPORTING i_result .

  CREATE OBJECT r TYPE c1.
  CALL METHOD r->(f) PARAMETER-TABLE ptab.
  write:/5 i_result .



Output


205






1.15  Use of Exception Table




Theme

Instead of dealing with each and every exception and assigning it to different   sy-subrc values, one can use exception table to handle the exceptions when a method is called dynamically.




The class C1 contains method M1 which raises an exception. Exception table ETAB is used to handle the exception.


REPORT  YSUBOOPS25 .
CLASS cl_abap_objectdescr DEFINITION LOAD.

CLASS c1 DEFINITION.
  PUBLIC SECTION.
  METHODS m1 EXCEPTIONS exc.
ENDCLASS.

CLASS c1 IMPLEMENTATION.
  METHOD m1.
    RAISE exc.
  ENDMETHOD.
ENDCLASS.

DATA r TYPE REF TO object.

DATA f(3) TYPE c VALUE 'M1'.

DATA: etab TYPE abap_excpbind_tab,
      etab_line LIKE LINE OF etab.

START-OF-SELECTION.

  etab_line-name = 'EXC'.
  etab_line-value = 4.
  INSERT etab_line INTO TABLE etab.
  IF sy-subrc ne 0.
    EXIT.
  ENDIF.

  CREATE OBJECT r TYPE c1.

  CALL METHOD r->(f) EXCEPTION-TABLE etab.
  WRITE sy-subrc.

Output
4


OOABAP Interview Questions



"You found the information helpful and want to say thanks? Your donation is enough to inspire us to do more. Thanks a bunch!"

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Categories

ABAP (1) ABAP Interview Questions (112) ABAP Open SQL Statements (1) ABAP Syntax Rules (6) ABAP WORKBENCH (2) ABAP-Interview-Questions (52) ALE IDOC (6) ALE IDOC Interview Questions (6) ale-idoc (6) ALE-IDOC-Interview-Questions (19) ALV Interview Questions (5) ALV-Interview-Questions (22) BADI (2) BAPI (1) BAPI Interview Questions (1) BAPI-Interview-Questions (14) BDC (6) BDC Interview Questions (6) BDC-Interview-Questions (9) big data (2) big data interview questions (1) Classical Reports Interview Question (3) Classical-Reports-Interview-Questions (22) Conditional Statements (1) Cross Applications (3) Cross-Applications (14) Data Dictionary (22) Data Type Questins (1) Data types (1) Data-Dictionary (48) Data-Type-Questins (6) Dialog programming (5) Dialog Programming Interview Questions (4) Dialog-Programming (30) DOMAIN Interview Questions (1) Domain-Interview-Questions (8) Function Module (2) hadoop (2) hadoop interview questions (2) hdfs (1) IDoc Tutorials (6) Interactive Report Interview Questions (4) Interactive-Reports-Interview-Questions (22) Internal Tables (1) interview questions (1) Lock Object Interview Questions (1) Lock-Objects-Interview-Questions (10) Logical Database (1) Modularization Interview Questions (4) Modularization-Interview-Questions (25) Module Pool Programming (5) Module-Pool-Programming (39) modules in sap (1) Object Oriented ABAP (19) Object Oriented ABAP Interview Questions (15) object-oriented-abap (2) Object-Oriented-ABAP-Interview-Questions (34) OOABAP (9) Reports (14) Reports Interview Questions (9) Reports-Interview-Questions (19) RFC (1) RFC Interview Questions (1) RFC-Interview-Questions (14) RICEF (1) RICEF Objects (1) SAP (4) SAP ABAP (4) SAP ABAP Interview Questions (42) SAP ABAP Introduction (46) SAP ABAP Message Types (2) SAP BADI Interview Questions (2) SAP Basics (71) SAP Books (2) SAP Certification (1) SAP CONSULTANTS (5) SAP CRM (1) SAP ENHANCEMENTS (3) SAP EXITS (2) SAP EXITS ( SAP ENHANCEMENTS ) Interview Questions (1) SAP Free Books (1) SAP HR (2) SAP Lock Object (1) sap modules (2) SAP Open SQL Statements (1) SAP R/3 Architecture (4) SAP Search help (1) SAP Smartforms (1) SAP Smartforms Interview Questions (2) SAP Tables (5) SAP Tcodes (10) SAP Views (1) SAP Webdynpro ABAP (12) SAP Work Processors (2) SAP Workflow (3) SAP-BADI-Interview-Questions (11) SAP-Enhancements (39) SAP-Exits (39) SAP-Exits-Enhancements-Interview Questions (3) SAP-HANA (1) SAP-HANA-Interview-Questions (1) SAP-Smartforms-Interview-Questions (2) SAP-Workflow (3) Scripts (3) Scripts Interview Questions (2) Scripts-Interview-Questions (32) Search Help Interview Questions (1) Search-Help-Interview-Questions (9) Smartforms (1) Table Maintenance Generator (1) Table-Maintenance-Generator (4) Tables in SAP (2) Tables Interview Questions (3) Tables-Interview-Questions (3) Type Group Interview Questions (1) Type-Group-Interview-Questions (7) Variable Declaration (1) Views Interview Questions (1) Views-Interview-Questions (5) Webdynpro (12) what is big data (1)

Protected Blog

 
This blog is not affiliated to SAP AG |SAP is trademark of SAP AG |The information collected from various sources use information with your own risk.