Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / OOPS ABAP / Classes & Objects

Classes & Objects

OOPS ABAP · ABAP Development ·

Open the interactive lesson →
  1. Procedural vs object-oriented
  2. Class and object, local vs global
  3. Defining a class
  4. Attributes
  5. Methods and parameters
  6. Creating objects, references and ME
  7. Constructors
  8. Visibility and encapsulation
  9. Friends, DEFERRED and LOAD
  10. Modern syntax quick reference
  11. Interview questions

The foundation of ABAP Objects: what a class and an object are, how to define a class, its attributes and methods, how objects are created and referenced, constructors, visibility, friends and the modern syntax. Inheritance, polymorphism, interfaces and casting follow on page 02; exceptions, events and design patterns on page 03.

Page at a glance

Mind map of this page: class, attributes, methods, objects and references, constructors, visibility and friends around the idea class = blueprint, object = instance

Part 1 – Procedural vs object-oriented

Procedural (structured, modular) languages such as C, Pascal and COBOL put the emphasis on functions: data and functions are kept apart, any routine can read and change the data, and functions are grouped by modularization. Object-oriented languages (Java, C++, C#) bundle the data with the methods that guard it into objects that model real-world things (a car, a person, a traffic light).

Procedural (data and functions separated) vs object-oriented (objects encapsulate data and methods) – real-world things become objects
  • ABAP is a hybrid language: classic procedural ABAP (reports, FORMs, function modules) plus ABAP Objects. New code – RAP, ABAP Cloud, BAdIs, ALV with classes – is object-oriented.

The four OO principles

Principle

Meaning

How ABAP achieves it

Encapsulation

Bind data and the methods that work on it into one unit; hide the internals (information hiding)

The class; visibility sections PUBLIC / PROTECTED / PRIVATE

Abstraction

Show only the essential behaviour, not how it is done

A small public API, abstract classes, interfaces (page 02)

Inheritance

A subclass takes over the components of its superclass

INHERITING FROM – reuse (page 02)

Polymorphism

"Many forms": one call, different behaviour depending on the object

Redefinition + interfaces with dynamic binding – reuse and enhancement (page 02)

Access specifiers implement encapsulation; abstraction is about exposing only what callers need (interfaces, abstract classes).

Benefits of ABAP Objects

  • Better reusability and data security (data can only change through the class's own methods).
  • Less complexity: each class has one job; easy to maintain, modify and extend.
  • Real-world entities (customer, sales order, connection) are modelled naturally.
  • Required for modern frameworks: RAP, BAdIs, SALV / ALV grid, ABAP Unit, ABAP Cloud.

Part 2 – Class and object, local vs global

A class is a template (blueprint) for objects. It declares attributes (data = the object's state) and methods (functions = its behaviour). An object is an instance of a class, created at runtime with its own copy of the instance attributes. Example: class employee; Jack and Rose are two employee objects.

  • Like TYPES in classic ABAP, the class definition itself creates no instance data. Memory for instance attributes is allocated only by CREATE OBJECT or NEW.
  • A loaded class does take memory: once a class is loaded, its static attributes and its code are in memory. Only the instance attributes wait for object creation.

Kinds of classes you will meet

Kind

What it is

Where

Usual class

Normal application logic

This page

Exception class

CX_… / ZCX_… class for class-based exceptions, optionally "with message class"

Page 03

Test class

ABAP Unit test: CLASS ltc_x DEFINITION FINAL FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. with concrete METHODS t1 FOR TESTING.

Page 03

Persistent class

Object Services: object state mapped to a DB table – Legacy, use RAP

Page 03

Abstract class

ABSTRACT – cannot be instantiated, only subclassed

Page 02

Final class

FINAL – cannot have subclasses

Page 02

Public / protected / private class

Who may create instances: CREATE PUBLIC | PROTECTED | PRIVATE

Part 8

Test methods are not abstract – they are normal (concrete) methods marked FOR TESTING. "Friend class" is a relationship (Part 9) and "singleton" a design pattern (Part 8, page 03), not class kinds.

Local vs global classes

Local class

Global class

Defined in

One program (report, function group, class pool include)

Class Builder SE24 or ADT (Eclipse); stored in its own class pool

Visible to

Only that program

Every program in the system (ABAP Cloud: if released / same software component)

Naming

lcl_… (test classes ltc_…)

ZCL_… / YCL_…, interfaces ZIF_…, exceptions ZCX_…

Typical use

Helper classes, report logic, test classes

Reusable logic, BAdI implementations, RAP behaviour pools

  • A global class pool has extra includes for local helpers. In ADT they are the tabs Class-relevant Local Types (CCDEF), Local Types (CCIMP), Test Classes (CCAU) and Macros (CCMAC).
  • SE24 is SAP GUI only; ABAP Cloud and RAP development is done in ADT.
A global class pool with its ADT tabs (Global Class, CCDEF, CCIMP, CCAU, CCMAC) next to a report with local lcl_ classes; global classes are usable everywhere, local ones only inside their program

Part 3 – Defining a class

A class has two parts: the definition (declares the components, split into visibility sections) and the implementation (the code of the methods). Neither part creates an object – together they are the template.

Anatomy of an ABAP class: definition with PUBLIC, PROTECTED and PRIVATE sections, implementation with METHOD blocks, usage with NEW and selectors
CLASS <class> DEFINITION
[PUBLIC]                        "only in a class pool (SE24 / ADT) = global class
[INHERITING FROM <superclass>]  "page 02
[ABSTRACT] [FINAL]
[CREATE {PUBLIC | PROTECTED | PRIVATE}]
[FOR TESTING]                   "ABAP Unit test class
[[GLOBAL] FRIENDS <class> ...].
PUBLIC SECTION.                     "components visible to everyone
PROTECTED SECTION.                  "visible in the class and its subclasses
PRIVATE SECTION.                    "visible only in the class itself (and its friends)
ENDCLASS.

CLASS <class> IMPLEMENTATION.
METHOD <method>.
...
ENDMETHOD.
ENDCLASS.
  • A class that declares methods needs an implementation part; a class with only attributes/types does not.
  • Writing PUBLIC after DEFINITION makes a class global only inside a class pool – you cannot turn a local class in a report into a global one. DEFERRED and LOAD are separate statement variants (Part 9), not additions to combine with the others, and the instantiation addition is written CREATE PUBLIC | PROTECTED | PRIVATE.
  • Local classes: the sections must appear in the order PUBLIC, PROTECTED, PRIVATE.
  • In a report, define and implement local classes at the top, then write START-OF-SELECTION. explicitly to mark where execution starts.

Components of a class

Component

Kinds

Declared with

Attributes

Instance, static, constants; plus local types

DATA, CLASS-DATA, CONSTANTS, TYPES

Methods

Instance, static; special: instance and static constructor; event handler methods

METHODS, CLASS-METHODS, constructor, class_constructor, FOR EVENT

Events

Instance and static events (page 03)

EVENTS, CLASS-EVENTS

Interfaces

Implemented interfaces (page 02)

INTERFACES

Aliases

Short names for interface components (page 02)

ALIASES

Friends and macros are not components – friendship is a relationship (Part 9), macros are a source section of the class pool.

A complete local class (runnable report)

REPORT zoo_demo_connection.

CLASS lcl_connection DEFINITION.
PUBLIC SECTION.
CONSTANTS c_max_seats TYPE i VALUE 300.    "constant: fixed for all objects
CLASS-DATA conn_counter TYPE i READ-ONLY.  "static: one value shared by all
METHODS constructor
IMPORTING iv_carrier_id    TYPE s_carr_id
iv_connection_id TYPE s_conn_id.
METHODS get_description RETURNING VALUE(rv_text) TYPE string.  "functional method
CLASS-METHODS get_count RETURNING VALUE(rv_count) TYPE i.
PRIVATE SECTION.
DATA carrier_id    TYPE s_carr_id.  "instance: one value per object
DATA connection_id TYPE s_conn_id.
ENDCLASS.

CLASS lcl_connection IMPLEMENTATION.
METHOD constructor.
carrier_id    = iv_carrier_id.
connection_id = iv_connection_id.
conn_counter  = conn_counter + 1.
ENDMETHOD.
METHOD get_description.
rv_text = |{ carrier_id } { connection_id }|.
ENDMETHOD.
METHOD get_count.
rv_count = conn_counter.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
DATA(lo_lh) = NEW lcl_connection( iv_carrier_id = 'LH' iv_connection_id = '0400' ).
DATA(lo_aa) = NEW lcl_connection( iv_carrier_id = 'AA' iv_connection_id = '0017' ).
DATA(lv_lh) = lo_lh->get_description( ).
DATA(lv_aa) = lo_aa->get_description( ).
DATA(lv_count) = lcl_connection=>get_count( ).
WRITE: / lv_lh, / lv_aa, / 'Objects created:', lv_count.  "LH 0400 / AA 0017 / 2

A global class skeleton (ADT)

CLASS zcl_demo_class DEFINITION PUBLIC FINAL CREATE PUBLIC.
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.                "lets you run the class with F9 in ADT
DATA        v_instance_attribute TYPE i.      "instance attribute
CLASS-DATA  v_static_attribute   TYPE i.      "static attribute
METHODS:       constructor, instance_method.  "instance methods
CLASS-METHODS: class_constructor, static_method.  "static methods
PROTECTED SECTION.                              "same kinds of components as PUBLIC
PRIVATE SECTION.
ENDCLASS.

CLASS zcl_demo_class IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.  "interface method: console output
out->write( |Static attribute = { v_static_attribute }| ).
ENDMETHOD.
METHOD constructor.       ENDMETHOD.
METHOD instance_method.   ENDMETHOD.
METHOD class_constructor. ENDMETHOD.
METHOD static_method.     ENDMETHOD.
ENDCLASS.

Running a class in ADT (IF_OO_ADT_CLASSRUN)

ABAP Cloud has no executable programs (reports), so the way to run code and see a result is a global class that implements the released interface IF_OO_ADT_CLASSRUN. When you press F9 (Run As › ABAP Application (Console)), ADT calls its method main and passes out, a reference to an output object. Everything written to out appears in the Console view. It works the same way in a classic system with ADT.

CLASS zcl_demo_run DEFINITION PUBLIC FINAL CREATE PUBLIC.
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.
ENDCLASS.

CLASS zcl_demo_run IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.
TYPES: BEGIN OF ty_conn,
carrier_id    TYPE c LENGTH 3,
connection_id TYPE n LENGTH 4,
END OF ty_conn,
ty_conns TYPE STANDARD TABLE OF ty_conn WITH EMPTY KEY.
DATA(lt_list) = VALUE ty_conns( ( carrier_id = 'LH' connection_id = '0400' )
( carrier_id = 'AA' connection_id = '0017' ) ).
out->write( data = lt_list name = `lt_list` ).  "table with a heading
out->write( |Today: { cl_abap_context_info=>get_system_date( ) DATE = ISO }| ).
ENDMETHOD.
ENDCLASS.
  • out->write( data = … name = … ): data takes any data object – elementary, structure or internal table – and formats it; the optional name becomes its heading. A string template works for plain text.
  • Only main is called: there is no selection screen and no user input. Put test values in the code, and use ABAP Unit (page 03) for checks you want to repeat.
  • Classic output such as WRITE lists and the demo class CL_DEMO_OUTPUT belongs to classic ABAP. In ABAP Cloud use out->write( ) (check the API state of any class in your system before you rely on it).
Running a class in ADT: implement IF_OO_ADT_CLASSRUN, press F9, read the output of out->write in the Console view

Documenting a class: ABAP Doc

ABAP Doc comments start with "! and stand directly before a declaration – the class, a method, an attribute or a type. ADT shows them in the ABAP Element Info view and in the F2 pop-up wherever the element is used, so callers see the documentation without opening the class.

"! Reads flight connections of one airline
CLASS zcl_demo_connection DEFINITION PUBLIC FINAL CREATE PUBLIC.
PUBLIC SECTION.
"! Returns the text shown for a connection, for example LH 0400
"! @parameter carrier_id      | Airline code
"! @parameter connection_id   | Flight number
"! @parameter result          | Text for the user interface
"! @raising   zcx_demo_flight | The connection does not exist
METHODS get_description
IMPORTING carrier_id    TYPE string
connection_id TYPE string
RETURNING VALUE(result) TYPE string
RAISING   zcx_demo_flight.
ENDCLASS.
  • @parameter <name> | <text> documents a parameter, @raising <exception class> | <text> a declared exception. A normal " comment is not ABAP Doc and is not shown in Element Info.
  • Clean ABAP: write ABAP Doc for public APIs – classes and methods meant for other teams or applications, and every released API – not for internal helpers.
  • The example also shows the Clean ABAP naming style without prefixes (see Part 5); zcx_demo_flight stands for an exception class like those on page 03.

Part 4 – Attributes

An attribute is a variable of the class that stores data. Three kinds hold data; TYPES only defines templates.

Instance attributes

Static attributes

Constants

Keyword

DATA

CLASS-DATA ("class variables / class attributes")

CONSTANTS – value given with VALUE in the declaration

Belongs to

One object: every object gets its own memory for each instance attribute

The class: memory allocated once when the class is loaded, shared by all objects

The class: allocated once when loaded, never changes

Access

Only through an object: lo_obj->attr

Through the class: lcl=>attr (also lo->attr works, but the class form is clean style)

lcl=>c_name

Use it when

Each object needs a different value (carrier id)

All objects need one common value (object counter, buffer)

The value is fixed (max seats, status codes)

  • Types (TYPES) allocate no memory. Use them to declare variables, work areas or internal tables inside the class (or outside, as lcl=>ty_name, if they are public).
  • Instances of the same class share the static values but their instance values are independent: in the example in Part 3, lo_lh holds LH/0400 and lo_aa AA/0017, while conn_counter = 2 exists once. (The picture in Part 6 creates a third object, so its counter shows 3.)
  • READ-ONLY (public section): DATA status TYPE c LENGTH 1 READ-ONLY. – everyone may read it, only the class itself may change it. Details in Part 8.
  • Enumerations (7.51+): an enumerated type in the public section gives a method a parameter that accepts only the listed values. The enum constants are components of the class (lcl_order=>released). Syntax details in ABAP on HANA › 03 ABAP New Syntax 7.4/7.5+; RTTI for enums (CL_ABAP_ENUMDESCR) on page 03.
CLASS lcl_order DEFINITION.
PUBLIC SECTION.
TYPES: BEGIN OF ENUM ty_status,
open,
released,
closed,
END OF ENUM ty_status.
METHODS set_status IMPORTING iv_status TYPE ty_status.
ENDCLASS.

lo_order->set_status( lcl_order=>released ).         "OK: a value of ty_status
lo_order->set_status( 1 ).                           "syntax error: not a ty_status value
DATA(lv_name) = CONV string( lcl_order=>released ).  "'RELEASED'

Part 5 – Methods and parameters

A method is a block of code implemented once and called any number of times – the OO successor of subroutines and function modules (see CORE ABAP › 04 Modularization & Debugging).

Subroutine (obsolete)

Function module

Method

Defined

FORM … ENDFORM

FUNCTION … ENDFUNCTION in a function group (SE37)

METHOD … ENDMETHOD in a class

Called

PERFORM f

CALL FUNCTION 'F'

lo->m( ), lcl=>m( ), CALL METHOD

Parameters

USING, CHANGING, TABLES

IMPORTING, EXPORTING, CHANGING, TABLES, EXCEPTIONS

IMPORTING, EXPORTING, CHANGING, RETURNING, RAISING

Three steps: declare the method (prototype) in the definition, implement it in the implementation, call it from outside or from another method.

METHODS       <name> [IMPORTING ...] [EXPORTING ...] [CHANGING ...] [RETURNING VALUE(...)]
[RAISING zcx_...].  "instance method
CLASS-METHODS <name> ...                 "static method

METHOD <name>.
...
ENDMETHOD.

lo_obj-><name>( ... ).                      "instance method: through an object
lcl_class=>static_name( ... ).              "static method: through the class
CALL METHOD lo_obj-><name> EXPORTING ... .  "old long form – still valid

Instance vs static methods

Instance methods (METHODS)

Static methods (CLASS-METHODS)

Can use directly

All components of the class: instance, static, constants, types

Only static components, constants and types – no instance attributes, no ME

Called through

An object: lo->m( )

The class: lcl=>m( ) (an object also works)

Typical use

Behaviour of one object

Factories, utilities, get_instance( ) of a singleton

A static method can still work with an object it receives as a parameter or creates – it just has no "current" object of its own. And "an instance method can access everything" holds within its own class: a subclass method cannot touch the superclass's private components.

Parameter kinds

Kind

Direction

Rules

IMPORTING

Caller → method

Mandatory by default; OPTIONAL or DEFAULT <value> make it optional (SE24: "Optional" checkbox). Passed by reference it is read-only inside the method.

EXPORTING

Method → caller

Always optional for the caller; any number.

CHANGING

Both ways

Caller passes a variable, the method may change it.

RETURNING

Method → caller, one result

Exactly one per method, always VALUE( ), fully typed. Makes the method a functional method.

  • Declaration order: IMPORTING, EXPORTING, CHANGING, RETURNING, then RAISING (or classic EXCEPTIONS).
  • More additions: PREFERRED PARAMETER (which optional importing parameter a single unnamed value goes to) and IS SUPPLIED (inside the method: did the caller pass this optional parameter?).
  • Naming: many classic projects use prefixes – iv_ / ev_ / cv_ / rv_ (v = value, s = structure, t = table, o = object) or im_ / ex_ / ch_ / re_. SAP's Clean ABAP style guide recommends the opposite: drop all encoding prefixes (result = a + b instead of rv_result = iv_a + iv_b) and simply call the RETURNING parameter result. Follow your project's convention and know both views for interviews. The examples on this page keep the prefixes so the parameter kind stays visible.

Pass by reference vs pass by value

By default all parameters except RETURNING are passed by reference. Any IMPORTING, EXPORTING or CHANGING parameter can be declared VALUE(p); RETURNING must be.

Kind

By reference (default)

By value – VALUE(p)

IMPORTING

Points to the caller's variable; writing to it is a syntax error. Fastest.

Local copy – the method may change it, the caller never sees the change.

EXPORTING

Writes go straight into the caller's variable. Not cleared at the start – the method sees the caller's old value, so set it explicitly.

Starts initial, copied back only when the method ends normally (not after an exception).

CHANGING

Changes are visible to the caller at once, even if an exception follows.

Copy in, copy back at normal end only.

RETURNING

Not allowed

Always by value

Parameter directions from caller to method: IMPORTING in, EXPORTING out, CHANGING both ways, RETURNING one value back; by reference shares one memory cell, by value works on a copy copied back only at a normal end

The same three passing kinds are drawn for subroutines in CORE ABAP › 04 Modularization & Debugging.

Functional methods – the modern rules

A method with a RETURNING parameter is a functional method. Its call is an expression, so it can be used wherever a value is expected.

  • Since 7.40 SP02 a functional method may also have EXPORTING and CHANGING parameters. The old rule "only IMPORTING + RETURNING" (and "RETURNING cannot be combined with EXPORTING/CHANGING – prior EHP7") is outdated.
    • Allowed is not the same as recommended. Clean ABAP: use either RETURNING or EXPORTING or CHANGING, not a combination – several kinds of output parameters show that the method does more than one thing. Prefer RETURNING: shorter calls and method chaining.
  • One RETURNING parameter only; always by value. You cannot declare it OPTIONAL – but the caller may ignore the result (call it like a normal method).
  • Where it can be used: right side of assignments, logical expressions (IF, WHILE, CASE), arithmetic and string expressions, as an actual parameter of another method, and in method chains.
  • RETURN with a value (ABAP 7.58 and ABAP Cloud – check your release): in a functional method RETURN <expression>. assigns the expression to the RETURNING parameter and leaves the method at once, e.g. RETURN lv_net * lv_rate. or RETURN VALUE #( carrier_id = 'LH' ).
METHODS get_total RETURNING VALUE(rv_total) TYPE netwr.
METHODS is_valid  RETURNING VALUE(rv_valid) TYPE abap_bool.

DATA(lv_total) = lo_order->get_total( ).               "assignment
IF lo_order->get_total( ) > 100.                       "comparison
ENDIF.
IF lo_order->is_valid( ).                              "predicative call (no "= abap_true")
ENDIF.
lo_order->get_total( RECEIVING rv_total = lv_total ).  "long form with RECEIVING

Calling methods – all the shapes

lo->m( ).                       "no parameters
lo->m( 42 ).                    "one (preferred) importing parameter, unnamed
lo->m( iv_a = 1 iv_b = 2 ).     "only importing parameters: no EXPORTING needed
lo->m( EXPORTING iv_a = 1       "the method's IMPORTING = caller's EXPORTING
IMPORTING ev_result = DATA(lv_res)  "inline declaration of the result
CHANGING  cv_count  = lv_count ).
lcl_util=>to_upper( lv_text ).  "static method
DATA(lv_name) = lo->get_customer( )->get_name( ).  "method chaining (functional methods)

Remember: the caller's keywords are the mirror image of the signature – the method IMPORTs what the caller EXPORTs.

Part 6 – Creating objects, references and ME

Creating an object (instantiating the class) is two steps: declare a reference variable (it allocates no object, it can only point to one), then create the object – memory for the instance attributes is allocated and the reference points to it.

DATA lo_conn TYPE REF TO lcl_connection.  "step 1: reference variable, initial

CREATE OBJECT lo_conn  "step 2, classic
EXPORTING iv_carrier_id = 'LH' iv_connection_id = '0400'.

lo_conn = NEW #( iv_carrier_id = 'LH' iv_connection_id = '0400' ).  "step 2, NEW (7.40)

DATA(lo_conn2) = NEW lcl_connection( iv_carrier_id = 'AA'  "both steps in one line
iv_connection_id = '0017' ).
  • NEW #( ) takes the type from the target variable; NEW lcl_x( ) names the class (needed with inline DATA( )). With no parameters write NEW #( ) – at least one blank between the brackets.
  • Dynamic creation: CREATE OBJECT lo TYPE (lv_class_name). – the class name is known only at runtime. Only CREATE OBJECT can do this; NEW cannot take a dynamic class name. Constructor parameters are passed in a parameter table of type ABAP_PARMBIND_TAB (each value as a data reference). In ABAP Cloud the dynamic name must be a released class or one of your own.
DATA lo_obj TYPE REF TO object.         "generic: any class
DATA(lv_class)   = `LCL_CONNECTION`.    "name known only at runtime
DATA(lv_carrier) = CONV s_carr_id( 'LH' ).
DATA(lv_conn)    = CONV s_conn_id( '0400' ).
DATA(lt_par) = VALUE abap_parmbind_tab(
( name  = 'IV_CARRIER_ID'
kind  = cl_abap_objectdescr=>exporting
value = REF #( lv_carrier ) )
( name  = 'IV_CONNECTION_ID'
kind  = cl_abap_objectdescr=>exporting
value = REF #( lv_conn ) ) ).
CREATE OBJECT lo_obj TYPE (lv_class) PARAMETER-TABLE lt_par.
Reference variables, objects on the heap and the static attribute in the class area; copying a reference copies only the pointer; a third object without a reference is garbage-collected, which is why the counter shows 3

Reference semantics

  • lo_b = lo_a. copies the pointer, not the object – both variables now point to the same object; a change through lo_b is visible through lo_a.
  • IF lo_a IS BOUND. – does it point to an object? IS INITIAL – is it empty? CLEAR lo_a. – drop the pointer.
  • Calling a method through an initial reference raises CX_SY_REF_IS_INITIAL (short dump OBJECTS_OBJREF_NOT_ASSIGNED if not caught).
  • The garbage collector deletes an object as soon as no reference points to it any more – at the latest when the internal session ends. There is no explicit "delete object" statement.

Component selectors

Selector

Meaning

Example

->

Instance component through an object reference

lo_conn->get_description( )

=>

Static component or constant through the class (or interface) name

lcl_connection=>conn_counter

~

Interface component (page 02)

lo->zif_printable~print( )

->*

Dereference a data reference (not used for object references)

lr_data->*

Generic references: REF TO object and REF TO data

ABAP has two kinds of reference variables. An object reference (TYPE REF TO <class or interface>) points to an instance of a class. A data reference (TYPE REF TO <data type>) points to a data object – a variable, a structure, a table row or an anonymous data object. Each has a fully generic form: REF TO object for any object and REF TO data for any data.

Data reference: REF TO i or REF TO data points to a data object, dereferenced with ->*; object reference: REF TO lcl or REF TO object points to an instance, components with ->; REF TO object needs a cast before use

Data reference

Object reference

Declared

TYPE REF TO i, TYPE REF TO sflight, generic TYPE REF TO data

TYPE REF TO lcl_connection, TYPE REF TO zif_x, generic TYPE REF TO object

Points to

A data object (named or anonymous)

An instance of a class

Created with

REF #( lv_var ), NEW i( 5 ), CREATE DATA lr TYPE (name)

NEW lcl_x( ), CREATE OBJECT lo TYPE (name)

Access

lr->* (the whole data object), lr->comp (component of a structure)

lo->attr, lo->meth( )

Generic form

REF TO data: dereference with ->*; older releases allow it only in ASSIGN lr->* TO <fs>, current ones in many more positions

REF TO object: no component access until you cast (CAST, ?=) or call the method dynamically (page 02)

DATA lv_num TYPE i VALUE 5.
DATA(lr_num) = REF #( lv_num ).               "data reference to a named variable
lr_num->* = lr_num->* + 1.                    "lv_num is now 6

DATA lr_any TYPE REF TO data.                 "generic data reference
lr_any = NEW string( `hello` ).               "anonymous data object
CREATE DATA lr_any TYPE ('SFLIGHT').          "type known only at runtime
ASSIGN lr_any->* TO FIELD-SYMBOL(<ls_any>).   "works in every release

DATA lo_any TYPE REF TO object.               "generic object reference
lo_any = NEW lcl_connection( iv_carrier_id = 'LH' iv_connection_id = '0400' ).
"lo_any->get_description( ).                  "syntax error: OBJECT has no such method
DATA(lo_c) = CAST lcl_connection( lo_any ).   "down cast (page 02)
DATA(lv_text) = lo_c->get_description( ).
CALL METHOD lo_any->('GET_DESCRIPTION') RECEIVING rv_text = lv_text.  "dynamic call
  • Both kinds follow the same reference semantics: copying copies the pointer, IS BOUND checks the target, and the garbage collector frees a target nobody references.
  • An object reference is never dereferenced with ->*, and methods cannot be called through a data reference.

ME – the self-reference

ME is an implicit, read-only reference variable that points to the object whose instance method is running. No object is created for it; ME is just a pointer to the current one. It does not exist in static methods.

  • Use it to make an attribute explicit when a local variable or parameter has the same name: me->carrier_id = carrier_id.
  • Pass the current object to others: lo_logger->register( me )., SET HANDLER on_click FOR me. (page 03), or return ro_self = me. to allow chaining.

Part 7 – Constructors

Constructors are special methods that initialise a class or an object. They are never called explicitly – the runtime calls them automatically.

Analogy: a report's INITIALIZATION event fills selection-screen fields with defaults. Without a constructor, a new object's attributes start with each type's initial value (or VALUE); with a constructor they start with whatever the constructor sets.

Instance constructor

Static constructor

Declaration

METHODS constructor IMPORTING … [RAISING …].

CLASS-METHODS class_constructor.

Parameters

Only IMPORTING (mandatory or optional) and exceptions

None, and no exceptions

Runs

Once for every object, during NEW / CREATE OBJECT

Once per class per internal session, just before the class is first used

Visibility

Public normally. Local classes: may sit in a section at least as visible as the CREATE addition (e.g. PRIVATE in a local CREATE PRIVATE singleton). Global classes: keep it in the PUBLIC section, even with CREATE PRIVATE – needed for correct compilation and syntax checks; CREATE PRIVATE still stops outsiders from creating objects

Always public section

Typical use

Check and store the values passed at creation

Fill static attributes once: buffers, customizing reads

  • The static constructor runs before the first of: creating an object, accessing a static attribute, calling a static method, registering a static event handler – also when a subclass is used first.
  • Declaring DATA lo TYPE REF TO lcl_x. triggers nothing – no constructor runs until the class is actually used.
  • If the instance constructor has mandatory IMPORTING parameters, you must pass them at creation: NEW lcl_x( iv_id = 1 ).
  • If the instance constructor raises an exception, the object is not created and the reference keeps its old value.
Constructor sequence: static constructor once before first use, instance constructor for every object; with inheritance static super to sub, instance via super->constructor

Sequence of execution

  • Class with both constructors, first object created before any static access: static constructor, then the instance constructor for that object. From the second object on, only the instance constructor.
  • Static access first (e.g. lcl=>get_count( )): the static constructor runs then; later objects run only the instance constructor.
  • With inheritance: static constructors run top-down (superclass first, each once), and every subclass constructor must call super->constructor( ). The five scenarios are on page 02 (Constructors in subclasses).

Normal vs special methods

Normal methods

Special methods (constructors)

Section

Any section

Static constructor public only; instance constructor usually public (see above)

Call

Explicitly, any number of times on the same object

Implicitly: instance constructor once per object, static constructor once per class and session

Parameters

IMPORTING, EXPORTING, CHANGING, RETURNING, RAISING

Instance: IMPORTING + exceptions; static: none

Return values

Any number (EXPORTING/CHANGING) or one RETURNING

Never

Only the static constructor must always be public; in a local class the instance constructor may also be declared in the protected or private section. In a global class, leave it public (Clean ABAP: "If your global class is CREATE PRIVATE, leave the CONSTRUCTOR public").

Part 8 – Visibility and encapsulation

Visibility works on two levels: component level – who may access an attribute or method – and class level – who may create instances (CREATE …).

Visibility matrix: public, protected and private components seen from the class, a subclass, a friend and the outside; class-level CREATE PUBLIC, PROTECTED, PRIVATE

Section

Same class

Subclasses

Outside (other classes, programs)

Role

PUBLIC

Yes

Yes

Yes

The class's interface to its users

PROTECTED

Yes

Yes

No

A special interface between a class and its subclasses

PRIVATE

Yes

No (inherited, but not visible)

No

Internal – not part of any interface

Friends (Part 9) may access protected and private components too. Private components are inherited – they exist in every subclass object and the superclass's methods use them – but the subclass cannot see them (page 02).

Encapsulation in practice

Client programs should not change attributes directly. They call a method that checks consistency – for example whether the carrier and connection combination is valid – and rejects invalid values. Then no other part of the program can bypass the check, knowingly or by accident. This is one of the main advantages of OO.

lo_conn->set_attributes( iv_carrier_id = 'LH' iv_connection_id = '0400' ).  "OK: it checks
lo_conn->carrier_id = 'XY'.  "not possible if carrier_id is PRIVATE or READ-ONLY –
"direct access would bypass the consistency check

Two ways to restrict access to an attribute:

Option

Declaration

Outside the class

READ-ONLY

Keep it in the PUBLIC section: DATA carrier_id TYPE s_carr_id READ-ONLY.

Read allowed, write forbidden

PRIVATE / PROTECTED

Move it to the PRIVATE (or PROTECTED) section

Read and write forbidden; offer getter/setter methods

  • READ-ONLY is used in the public section (and in interfaces).
  • ADT quick fix: put the cursor on the attribute, press Ctrl+1, choose "Make <attribute> private".
  • Rule of thumb: attributes in PRIVATE (or PROTECTED), methods in PUBLIC; access internal data only through public methods.

Class level: who may create instances

Addition

Instances can be created

Inheritance

CREATE PUBLIC (default)

Anywhere: in the class, in subclasses, outside

Can be inherited

CREATE PROTECTED

Only in methods of the class and of its subclasses

Can be inherited

CREATE PRIVATE

Only in methods of the class itself (and its friends) – outsiders get the object from a static method (factory, singleton)

Subclasses can only be instantiated if the superclass declares them a FRIEND – so make such classes FINAL

  • A subclass without its own CREATE addition takes over the superclass's setting and can override it explicitly (for CREATE PRIVATE only as a friend).
  • ABSTRACT is not a fourth "class visibility" – it is a separate addition (page 02).

Singleton (only one instance per session) – the classic use of CREATE PRIVATE. More patterns on page 03.

CLASS lcl_config DEFINITION FINAL CREATE PRIVATE.
PUBLIC SECTION.
CLASS-METHODS get_instance RETURNING VALUE(ro_instance) TYPE REF TO lcl_config.
PRIVATE SECTION.
CLASS-DATA go_instance TYPE REF TO lcl_config.
ENDCLASS.

CLASS lcl_config IMPLEMENTATION.
METHOD get_instance.
IF go_instance IS NOT BOUND.
go_instance = NEW #( ).  "allowed: we are inside the class
ENDIF.
ro_instance = go_instance.
ENDMETHOD.
ENDCLASS.

DATA(lo_cfg) = lcl_config=>get_instance( ).  "NEW lcl_config( ) outside = syntax error

Part 9 – Friends, DEFERRED and LOAD

Normally only public components are reachable from outside. A class can grant friendship to other classes (or interfaces): their methods may then access all its components, including protected and private ones.

CLASS lcl_auditor DEFINITION DEFERRED.  "forward declaration: defined further down

CLASS lcl_account DEFINITION FRIENDS lcl_auditor.
PRIVATE SECTION.
DATA balance TYPE p LENGTH 15 DECIMALS 2 VALUE '100.00'.
ENDCLASS.

CLASS lcl_auditor DEFINITION.
PUBLIC SECTION.
METHODS check IMPORTING io_account TYPE REF TO lcl_account
RETURNING VALUE(rv_balance) TYPE decfloat34.
ENDCLASS.

CLASS lcl_auditor IMPLEMENTATION.
METHOD check.
rv_balance = io_account->balance.  "allowed: lcl_account granted friendship to lcl_auditor
ENDMETHOD.
ENDCLASS.
  • Direction: CLASS a DEFINITION FRIENDS b. – A grants, B's methods get access to A. Objects of A used outside do not get extra access.
  • Friendship is one-way and not transitive (a friend of B is not a friend of A). Subclasses of the friend B are friends too; subclasses of A do not inherit A's friendships.
Friendship: lcl_account grants FRIENDS lcl_auditor; the auditor and its subclasses see the private section; a subclass of lcl_account and a friend of the auditor do not; LOCAL FRIENDS for unit tests, GLOBAL FRIENDS for global classes
  • Global classes: GLOBAL FRIENDS zcl_b (SE24: Friends tab). For unit tests a global class grants access to its local test class: CLASS zcl_x DEFINITION LOCAL FRIENDS ltc_x. (page 03).
  • Use friendship sparingly – it breaks encapsulation. Typical uses: test classes, factories, tightly coupled helper classes.

DEFERRED

CLASS lcl_b DEFINITION DEFERRED. tells the compiler that lcl_b is defined later in the program, so it can already be referenced (as a friend, or in TYPE REF TO). Needed only when the class is used before its definition – not always for friends.

LOAD – Legacy

CLASS zcl_x DEFINITION LOAD. (and INTERFACE zif_x LOAD.) is obsolete. It was only ever needed when a program failed to compile because of recursive access to global classes or interfaces. Such recursions are now avoided and the compiler ignores the statement; know it only if an interviewer asks.

Part 10 – Modern syntax quick reference

Classic

Modern (7.40+)

Note

DATA lo TYPE REF TO lcl_x. + CREATE OBJECT lo.

DATA(lo) = NEW lcl_x( ).

Inline declaration + NEW operator

CREATE OBJECT lo EXPORTING iv_a = 1.

lo = NEW #( iv_a = 1 ).

# = type of the target

CALL METHOD lo->m EXPORTING iv = 1 RECEIVING rv = lv.

lv = lo->m( 1 ).

Functional call

Helper variable for each step

lo->get_a( )->get_b( )->run( ).

Method chaining

CREATE OBJECT lo. lo->run( ).

NEW lcl_job( )->run( ).

Chaining on a new object

lo_sub ?= lo_super.

DATA(lo_sub) = CAST lcl_sub( lo_super ).

Down cast – page 02

All constructor expressions (VALUE, CORRESPONDING, CONV, COND, REF …) are covered in ABAP on HANA › 03 ABAP New Syntax 7.4/7.5+.

Part 11 – Interview questions

What is a class and what is an object? Does a class use memory?

A class is the blueprint: it declares attributes (state) and methods (behaviour). An object is an instance created at runtime with NEW or CREATE OBJECT, with its own copy of the instance attributes. The class itself creates no instance data, but once loaded its static attributes and code are in memory.

What are the OO principles, and what is the difference between encapsulation and abstraction?

Encapsulation, abstraction, inheritance, polymorphism. Encapsulation hides the data inside the class and allows changes only through its methods (visibility sections). Abstraction exposes only the essential behaviour – a small public API, abstract classes and interfaces – so callers don't depend on details.

Local vs global class?

A local class is defined inside one program and visible only there (lcl_…). A global class is created in SE24 or ADT, stored in a class pool and usable by all programs (ZCL_…). Global classes can have local helper and test classes in their own includes.

Instance vs static attributes and methods?

Instance components belong to one object (DATA, METHODS, accessed with ->). Static components belong to the class, exist once per session and are shared by all objects (CLASS-DATA, CLASS-METHODS, accessed with =>). Static methods cannot use instance attributes or ME directly.

What is a functional method? Can it have EXPORTING parameters?

A method with exactly one RETURNING parameter (always by value), so its call can be used in expressions, conditions and chains. Since 7.40 SP02 it may also have EXPORTING and CHANGING parameters; before that it could only have IMPORTING parameters besides RETURNING. Clean ABAP still advises using only one kind of output parameter per method.

Pass by value vs pass by reference in methods?

By reference (default) passes the address: IMPORTING is read-only, EXPORTING/CHANGING write directly into the caller's variable – and a by-reference EXPORTING parameter is not cleared at the start. By value (VALUE( )) works on a copy that is copied back only when the method ends normally. RETURNING is always by value.

What is ME?

An implicit, read-only reference variable pointing to the object whose instance method is running. It is used to address attributes hidden by local names (me->attr) or to pass the current object on. It does not exist in static methods.

CREATE OBJECT vs NEW?

Both create an object. NEW (7.40) is an expression: it can be used inline (DATA(lo) = NEW lcl_x( )), with # for the target type, directly in method calls and chains. CREATE OBJECT is the classic statement; its TYPE (name) variant creates an object of a class known only at runtime.

Instance vs static constructor – when do they run and in which order?

The static constructor (class_constructor, no parameters) runs once per internal session before the class is first used. The instance constructor (constructor, IMPORTING only) runs for every new object. For the first object: static first, then instance; afterwards only the instance constructor. With inheritance, static constructors run superclass first.

Explain PUBLIC, PROTECTED, PRIVATE and READ-ONLY.

Public components are visible everywhere, protected ones in the class and its subclasses, private ones only in the class (and its friends). READ-ONLY on a public attribute lets everyone read it but only the class change it.

What does CREATE PRIVATE do, and how do you build a singleton?

CREATE PRIVATE allows instances to be created only inside the class. A singleton combines CREATE PRIVATE (best also FINAL) with a private static attribute holding the one instance and a public static get_instance( ) method that creates it on first call and returns it.

What is a friend class? Is friendship inherited?

A class that has been granted access (CLASS a DEFINITION FRIENDS b) to all components of the granting class, including private ones. It is one-way and not transitive. Subclasses of the friend are also friends, but subclasses of the granting class do not pass the friendship on. Typical use: LOCAL FRIENDS for unit tests.

What is the difference between a data reference and an object reference?

A data reference (TYPE REF TO <data type>, generic REF TO data) points to a data object and is dereferenced with ->*; it is created with REF #( ), NEW type( ) or CREATE DATA. An object reference (TYPE REF TO <class or interface>, generic REF TO object) points to an instance of a class and reaches its components with ->; it is created with NEW or CREATE OBJECT. Through REF TO object you can call nothing until you cast it or use a dynamic call.

There are no reports in ABAP Cloud – how do you run a class?

Implement the released interface IF_OO_ADT_CLASSRUN in a global class and put the code in its method if_oo_adt_classrun~main. Pressing F9 in ADT runs it; out->write( data = … name = … ) sends data objects to the Console view. For repeatable checks use ABAP Unit tests instead.

What is ABAP Doc?

Documentation comments that start with "! directly before a declaration, with tags such as @parameter and @raising for the method signature. ADT shows them in the ABAP Element Info view and the F2 pop-up wherever the element is used. Clean ABAP recommends ABAP Doc for public APIs, not for internal code.

Should parameters have prefixes like iv_ and rv_? May one method mix RETURNING, EXPORTING and CHANGING?

Many classic projects use prefixes and you should follow the project's convention. SAP's Clean ABAP guide recommends dropping encoding prefixes and naming the RETURNING parameter result. Mixing output kinds is allowed since 7.40 SP02, but Clean ABAP says to use only one of RETURNING, EXPORTING or CHANGING, preferably RETURNING, because several output kinds suggest the method does more than one thing.

🏠 Start Here · 02 · Inheritance & Interfaces ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC

Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | EHS ABAP | HR ABAP | BW | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP