[ABAP] How do I define and use classes and objects in ABAP?

In ABAP, classes can be defined using the keyword "CLASS" followed by the class name. Objects of these classes can be created using the "CREATE OBJECT" statement. Here's a step-by-step guide on defining and using classes and objects in ABAP:

  1. Define a class:

    • Go to the ABAP Development Tools (ADT) perspective in SAP NetWeaver or SAP GUI.
    • Create a new ABAP Class using the "New ABAP Class" option.
    • Provide a name for the class and define its visibility (private, protected, or public).
    • Define the attributes (data members) and methods (member functions) of the class.
  2. Define methods:

    • In the class editor, switch to the "Methods" tab.
    • Define the methods by providing a name, visibility, and return type.
    • Implement the method logic within the method body.
  3. Define attributes:

    • In the class editor, switch to the "Attributes" tab.
    • Define the attributes by providing a name, data type, and visibility.
  4. Save and activate the class.

  5. Create an object:

    • In your ABAP program/report, declare a variable of the class type.
    • Use the "CREATE OBJECT" statement to create an instance of the class and assign it to the variable.
  6. Use the object:

    • Access the attributes and methods of the object using the "->" operator.
    • Call the methods using the object reference and appropriate parameters.

Here's an example to illustrate the above steps:

 1CLASS lcl_my_class DEFINITION.
 2  PUBLIC SECTION.
 3    METHODS:
 4      constructor,
 5      display_msg IMPORTING iv_msg TYPE string,
 6      get_msg RETURNING VALUE(rv_msg) TYPE string.
 7  PRIVATE SECTION.
 8    DATA:
 9      mv_msg TYPE string.
10ENDCLASS.
11
12CLASS lcl_my_class IMPLEMENTATION.
13  METHOD constructor.
14    mv_msg = ''.
15  ENDMETHOD.
16
17  METHOD display_msg.
18    WRITE iv_msg.
19    mv_msg = iv_msg.
20  ENDMETHOD.
21
22  METHOD get_msg.
23    rv_msg = mv_msg.
24  ENDMETHOD.
25ENDCLASS.
26
27DATA: lo_my_object TYPE REF TO lcl_my_class.
28
29CREATE OBJECT lo_my_object.
30
31lo_my_object->display_msg( 'Hello World!' ).
32
33DATA(lv_msg) = lo_my_object->get_msg( ).
34WRITE lv_msg.

In the above example, a class named "lcl_my_class" is defined with a constructor, "display_msg" method, and "get_msg" method. An object "lo_my_object" is created using the "CREATE OBJECT" statement. The "display_msg" method is called to display a message, and then the "get_msg" method is called to retrieve the stored message and display it.