ABAP Objects arrived in 1999 and is now the standard way to write ABAP.
Class structure
CLASS lcl_order DEFINITION.
PUBLIC SECTION.
METHODS constructor IMPORTING iv_order_id TYPE vbeln.
METHODS get_total RETURNING VALUE(rv_total) TYPE p LENGTH 8 DECIMALS 2.
CLASS-METHODS create_from_db
IMPORTING iv_order_id TYPE vbeln
RETURNING VALUE(ro_order) TYPE REF TO lcl_order.
PRIVATE SECTION.
DATA mv_order_id TYPE vbeln.
DATA mt_items TYPE ty_items.
ENDCLASS.
CLASS lcl_order IMPLEMENTATION.
METHOD constructor.
mv_order_id = iv_order_id.
ENDMETHOD.
ENDCLASS.| Section | Accessible from |
|---|---|
| PUBLIC | Anywhere |
| PROTECTED | The class and its subclasses |
| PRIVATE | The class only |
Instance and static
| Kind | Keyword | Access |
|---|---|---|
| Instance attribute | DATA | obj->attr |
| Static attribute | CLASS-DATA | class=>attr |
| Instance method | METHODS | obj->method( ) |
| Static method | CLASS-METHODS | class=>method( ) |
DATA(lo_order) = NEW lcl_order( iv_order_id = '0000012345' ).
DATA(lv_total) = lo_order->get_total( ).
DATA(lo_new) = lcl_order=>create_from_db( '0000012345' ).Inheritance
CLASS lcl_rush_order DEFINITION INHERITING FROM lcl_order.
PUBLIC SECTION.
METHODS get_total REDEFINITION.
ENDCLASS.
CLASS lcl_rush_order IMPLEMENTATION.
METHOD get_total.
rv_total = super->get_total( ) * '1.2'.
ENDMETHOD.
ENDCLASS.ABAP supports single inheritance only. To combine behaviours, use interfaces.
Interfaces
INTERFACE lif_printable.
METHODS print.
ENDINTERFACE.
CLASS lcl_invoice DEFINITION.
PUBLIC SECTION.
INTERFACES lif_printable.
ENDCLASS.
CLASS lcl_invoice IMPLEMENTATION.
METHOD lif_printable~print.
WRITE: / 'Printing the invoice'.
ENDMETHOD.
ENDCLASS.
DATA lo_printable TYPE REF TO lif_printable.
lo_printable = NEW lcl_invoice( ).
lo_printable->print( ).Interfaces let unrelated classes be treated uniformly โ invoices and delivery notes both handled as printable things. They also make substituting a mock object for testing straightforward.
Exception classes
IF sy-subrc <> 0.
RAISE EXCEPTION TYPE zcx_customer_not_found
EXPORTING customer_id = iv_kunnr.
ENDIF.
TRY.
DATA(ls_customer) = lo_service->get_customer( '0000001000' ).
CATCH zcx_customer_not_found INTO DATA(lx_notfound).
MESSAGE lx_notfound->get_text( ) TYPE 'E'.
CATCH cx_root INTO DATA(lx_root).
MESSAGE lx_root->get_text( ) TYPE 'E'.
ENDTRY.| Class | Behaviour |
|---|---|
| CX_STATIC_CHECK | Must be declared and handled |
| CX_DYNAMIC_CHECK | Checked at runtime; no declaration needed |
| CX_NO_CHECK | Neither declared nor caught; for fatal errors |