Create Local Class in OO ABAP

0
5855

[adsenseyu2]

In this tutorial, we will learn how to create a Local class in OO ABAP. In core ABAP, we modularize the ABAP code using function modules and subroutines. We can also modularize the same code in object oriented approach by creating local classes in the program. There are two parts involved while creating local classes, they are

  • Definition
  • Implementation

In Definition part we define all the attributes and methods with access specifiers(mandatory) and all DATA and TYPES declaration are defined in Definition section of the class.

We implement the methods i.e we write the abap code in the methods, in Implementation section of the class.

Definition

** Class Definition
CLASS lcl_demo DEFINITION.

  PUBLIC SECTION.                           "<< Access Specifier

* TYPE Declarations
    TYPES: BEGIN OF lty_hello,
           name       TYPE char10,
           age        TYPE char10,
           vbeln      TYPE vbeln,
           END OF lty_hello.

* DATA Declarations
    DATA: lv_hello    TYPE string,
          lt_hello    TYPE STANDARD TABLE OF lty_hello,
          ls_hello    TYPE lty_hello.

* METHOD Definitions
    METHODS: say_hello.
ENDCLASS.

Implementation

** Class Implementation
CLASS lcl_demo IMPLEMENTATION.

  METHOD say_hello.
    WRITE : 'Hello OO ABAP. How are you?'.
  ENDMETHOD.                    "say_hello


ENDCLASS.                    "lcl_demo IMPLEMENTATION

[adsenseyu1]

As you are ready with Class Definition and Class Implementation, our next step would be how to call the attributes and methods which are defined in class. To access any components of the class first we need to instantiate the class (or) in other words we need to create object for the class(except for static components).

To create object for the class we use the below two lines of code.

START-OF-SELECTION.
* Instantiate the Class/Create object for the class 
DATA: lo_demo TYPE REF TO lcl_demo. 
CREATE OBJECT lcl_demo.

To access the attributes and methods of local class

lo_demo->say_hello( ).         "Call Methods.
lo_demo->lv_hello = 'Welcome'. "Class attributes.
WRITE:/ lo_demo->lv_hello.

Now you know how create program and modularize the abap code using object oriented approach. Now pick up old program which are based on procedural paradigm and convert them into object oriented programs. Try to adopt the object oriented style in your future programs you develop.