ABAP Tutorial
Chapter III OO Programming in ABAP
1 Defining and implementing methods
To use a method in a program, we need to
-
1. define
-
2. and implement it.
The definition occurs in a class with opening tag CLASS and closing tag ENDCLASS.
In the definition we tell the program which parameters the method is going to receive or return. In the case of factorial we are going to pass a parameter called n (of type decfloat34) to factorial. The method is going to return a value called returnvalue.
CLASS cl_helloworld DEFINITION. PUBLIC SECTION. METHODS: factorial IMPORTING n TYPE decfloat34 RETURNING VALUE(returnvalue) TYPE decfloat34. ENDCLASS.
Listing III.1: The definition of a method in a class
The IMPLEMENTATION of a method uses the parameter names of the definition to instruct how these parameters process the data.
CLASS cl_helloworld IMPLEMENTATION. METHOD factorial. IF n = 0 OR n = 1. returnvalue = 1. ELSE. returnvalue = n * ( me->factorial( n - 1 ) ). ENDIF. ENDMETHOD. ENDCLASS.
Listing III.2: The implementation of a Class
As you can see, we can use our factorial function recursively by calling it. However, methods need to be called on objects. When recursing, the object is referenced as me->.
PARAMETERS P_input TYPE decfloat34. DATA: lo_hello_world TYPE REF TO cl_helloworld, myresult TYPE decfloat34. START-OF-SELECTION. CREATE OBJECT lo_hello_world. myresult = lo_hello_world->factorial( P_input ). WRITE myresult.
Listing III.3: Calling a method in a program