Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / OOPS ABAP / Inheritance, Polymorphism & Interfaces

Inheritance, Polymorphism & Interfaces

OOPS ABAP · ABAP Development ·

Open the interactive lesson →
  1. Inheritance
  2. Redefinition, SUPER and FINAL
  3. Constructors in subclasses
  4. Polymorphism
  5. Abstract classes and methods
  6. Interfaces
  7. Casting: up cast and down cast
  8. Dynamic method calls
  9. UML notation
  10. Interview questions

How classes build on each other: inheritance, redefinition, constructors in subclasses, polymorphism, abstract and final classes, interfaces, and up/down casting with SAP's current terms. Classes, attributes, methods, constructors and visibility are on page 01; exceptions, events and design patterns on page 03.

Page at a glance

Mind map of page 02: inheritance, redefinition, subclass constructors, polymorphism, abstract classes, interfaces and BAdIs, casting and dynamic calls around the idea "reuse and substitute"

Part 1 – Inheritance

Inheritance = a new class (subclass, derived class) takes over all components of an existing class (superclass, base class) and adds or changes behaviour. The superclass gives, the subclass takes. Goal: reuse – write common code once – and an "is-a" relationship (a bike is a vehicle).

CLASS lcl_cycle DEFINITION INHERITING FROM lcl_vehicle.  "subclass of lcl_vehicle
PUBLIC SECTION.
METHODS setcycle.        "new component
PROTECTED SECTION.
DATA color TYPE string.  "new component
ENDCLASS.
Inheritance tree Vehicle → Cycle → Bike: inherited and new components, private components inherited but not visible, FINAL class at the bottom

Rules

  • A class has exactly one direct superclass. Classes without INHERITING FROM inherit implicitly from the root class OBJECT.
  • Private components are inherited – they exist in every subclass object and the superclass's own methods keep using them – but they are not visible in the subclass. Public and protected components are visible.
  • A subclass can add components and redefine instance methods (Part 2). It cannot remove inherited components or change their visibility.
  • A static attribute exists once for the whole hierarchy: superclass and subclasses share the same value.
  • A FINAL class cannot have subclasses: CLASS lcl_bike DEFINITION INHERITING FROM lcl_cycle FINAL.

Kinds of inheritance

Kind

Shape

In ABAP?

Single

One subclass, one superclass (Teacher ← Student)

Yes

Multilevel

A subclass of a subclass (Grandparent ← Parent ← Child, Vehicle ← Cycle ← Bike)

Yes

Hierarchical

One superclass, many subclasses (Vehicle ← Cycle, Vehicle ← Car)

Yes

Multiple

One class with several superclasses

No for classes. A class can implement any number of interfaces – that gives multiple type inheritance, but no inherited code

Single, multilevel, hierarchical and multiple inheritance (multiple only via interfaces in ABAP)

Multiple inheritance in ABAP means one superclass plus any number of interfaces – the picture's "multiple" case works only because Father and Mother are interfaces.

Part 2 – Redefinition, SUPER and FINAL

Method overriding (redefinition): a subclass gives an inherited instance method a new implementation. Re-declare it with REDEFINITION and implement it again. Inside, super->method( ) calls the superclass's implementation – reuse it, then add to it.

REPORT zoo_demo_inheritance.

CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS constructor IMPORTING iv_wheels TYPE i.
METHODS describe RETURNING VALUE(rv_text) TYPE string.
PROTECTED SECTION.
DATA wheels TYPE i.
ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION.
METHOD constructor.
wheels = iv_wheels.
ENDMETHOD.
METHOD describe.
rv_text = |Vehicle with { wheels } wheels|.
ENDMETHOD.
ENDCLASS.

CLASS lcl_cycle DEFINITION INHERITING FROM lcl_vehicle.
PUBLIC SECTION.
METHODS constructor IMPORTING iv_color TYPE string.
METHODS describe REDEFINITION.  "same name, same signature, same section
PROTECTED SECTION.
DATA color TYPE string.
ENDCLASS.

CLASS lcl_cycle IMPLEMENTATION.
METHOD constructor.
super->constructor( iv_wheels = 2 ).  "first: build the vehicle part
color = iv_color.
ENDMETHOD.
METHOD describe.
rv_text = super->describe( ) && |, colour { color }|.  "reuse + extend
ENDMETHOD.
ENDCLASS.

CLASS lcl_bike DEFINITION INHERITING FROM lcl_cycle FINAL.
PUBLIC SECTION.
METHODS constructor IMPORTING iv_color TYPE string iv_gears TYPE i.
METHODS describe REDEFINITION.
PRIVATE SECTION.
DATA gears TYPE i.
ENDCLASS.

CLASS lcl_bike IMPLEMENTATION.
METHOD constructor.
super->constructor( iv_color = iv_color ).
gears = iv_gears.
ENDMETHOD.
METHOD describe.
rv_text = super->describe( ) && |, { gears } gears|.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
DATA lt_vehicles TYPE STANDARD TABLE OF REF TO lcl_vehicle WITH EMPTY KEY.
lt_vehicles = VALUE #( ( NEW lcl_vehicle( 4 ) )
( NEW lcl_cycle( `red` ) )
( NEW lcl_bike( iv_color = `black` iv_gears = 21 ) ) ).
LOOP AT lt_vehicles INTO DATA(lo_vehicle).
DATA(lv_text) = lo_vehicle->describe( ).  "each object runs its OWN describe (Part 4)
WRITE / lv_text.
ENDLOOP.

Output: "Vehicle with 4 wheels" / "Vehicle with 2 wheels, colour red" / "Vehicle with 2 wheels, colour black, 21 gears".

Redefinition chain: lo_vehicle->describe( ) on a bike object runs lcl_bike's describe, which calls super->describe( ) in lcl_cycle, which calls super->describe( ) in lcl_vehicle; the text grows on the way back

Redefinition rules

  • Only instance methods that are public or protected and not FINAL can be redefined.
  • The signature cannot change (parameters, types) and neither can the visibility section or the category (instance/static).
  • Cannot be redefined: static methods, private methods, FINAL methods, constructors (each class has its own constructor instead – Part 3).
  • super->m( ) works only inside the redefinition of m itself. Calling it is recommended but not mandatory (except super->constructor( )).
  • A redefinition can itself be closed: METHODS describe FINAL REDEFINITION.
  • Interface methods implemented in a superclass can be redefined too: METHODS lif_x~m REDEFINITION.

FINAL – two levels

Effect

Syntax

FINAL class

No subclasses at all (all its methods are implicitly final)

CLASS lcl_x DEFINITION FINAL.

FINAL method

Inherited, but cannot be redefined in subclasses. Useful only for public/protected instance methods – static and private methods can't be redefined anyway, so FINAL is not allowed or meaningless there

METHODS m FINAL.

Overloading – not supported in ABAP

Method overloading (C++/Java) = several methods with the same name but different parameters. ABAP does not allow two methods with the same name in one class, so this is a syntax error:

METHODS m1.
METHODS m1 IMPORTING x TYPE i.  "syntax error: m1 already declared
METHODS m1 IMPORTING x TYPE c.
METHODS m1 IMPORTING x TYPE i y TYPE i.
  • Workarounds: OPTIONAL / DEFAULT parameters with IS SUPPLIED, generic types (next section), or different method names (create_from_id, create_from_name).
  • So in ABAP, polymorphism = redefinition + interfaces, not overloading.

Generic parameter typing instead of overloading

Where Java would overload log( int ), log( String ), log( Date ), ABAP declares one method with a generic type. The actual type is fixed by the argument at runtime; the method only uses operations that make sense for every type the generic type allows.

Generic type

Accepts

Typical use

any / data

Any data type (a data parameter cannot be used in numeric, description or arithmetic functions)

Fully generic helpers; work with ASSIGN and RTTI (page 03)

simple

Any elementary type and flat character-like structures

Formatting, logging one value

numeric, clike, csequence

Numeric types; character-like types; c and string

Calculations; text handling

ANY TABLE, INDEX TABLE, STANDARD TABLE

Any internal table; index tables; standard tables

Table utilities (lines( ), LOOP, INSERT)

REF TO data

A reference to any data object (complete type)

Pass data of unknown type by reference

REF TO object

A reference to any object – every class inherits from OBJECT (complete type)

Frameworks; to use the object, down cast or call dynamically (Parts 7 and 8)

CLASS lcl_formatter DEFINITION.
PUBLIC SECTION.
METHODS to_text   IMPORTING iv_value        TYPE simple     "i, p, d, string, c ...
RETURNING VALUE(rv_text)  TYPE string.    "complete type only
METHODS row_count IMPORTING it_table        TYPE ANY TABLE  "any internal table
RETURNING VALUE(rv_count) TYPE i.
ENDCLASS.

CLASS lcl_formatter IMPLEMENTATION.
METHOD to_text.
rv_text = |{ iv_value }|.
ENDMETHOD.
METHOD row_count.
rv_count = lines( it_table ).
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
DATA lt_carriers TYPE STANDARD TABLE OF scarr WITH EMPTY KEY.
DATA(lo_fmt) = NEW lcl_formatter( ).
DATA(lv_1) = lo_fmt->to_text( 42 ).          "integer
DATA(lv_2) = lo_fmt->to_text( sy-datum ).    "date
DATA(lv_3) = lo_fmt->to_text( `ABAP` ).      "string
DATA(lv_n) = lo_fmt->row_count( lt_carriers ).
  • Generic types are allowed for IMPORTING, EXPORTING and CHANGING parameters. A RETURNING parameter must be completely typed – TYPE REF TO data and TYPE REF TO object count as complete.
  • object can only be written after REF TO: TYPE REF TO object is fine, TYPE object is not.
  • The more generic the type, the less the compiler can check – errors move to runtime. For objects, an interface type (TYPE REF TO lif_printable) is usually better than REF TO object: it is still open to many classes, but the compiler knows the methods.
  • Data references vs object references (->* vs ->, CREATE DATA) are compared on page 01.

Part 3 – Constructors in subclasses

Every class has its own instance constructor – constructors are not redefined, and a subclass constructor may have a different signature from its superclass's.

  • If a subclass declares its own instance constructor, it must call super->constructor( … ) – even if the superclass declares no constructor explicitly (only direct subclasses of OBJECT are exempt).
  • Before that call the subclass constructor cannot use instance attributes or ME – only its parameters and static components. So in practice super->constructor( ) is the first statement.
  • A subclass without its own constructor uses the superclass's constructor – including its parameters.
  • Static constructors are independent: when a subclass is used first, the static constructors of all superclasses not yet run go first, top-down.

Scenario

Setup

What runs (first subclass object, no earlier access)

Later objects

1

Super: static + instance ctor. Sub: none

Super static → super instance

Super instance only

2

Super: static + instance. Sub: static only

Super static → sub static → super instance

Super instance only

3

Both have static + instance; sub calls super->constructor( )

Super static → sub static → sub constructor starts → super->constructor( ) runs the super body → rest of the sub body

Instance constructors only, same nesting

4

Both instance ctors have mandatory parameters

Pass the sub's parameters at NEW lcl_sub( … ); the sub constructor passes the super's values in super->constructor( … )

Same

5

Super ctor has mandatory parameters, sub has none

Pass the super constructor's parameters at NEW lcl_sub( … )

Same

Order of execution (scenario 3): execution enters the subclass constructor first, but the superclass constructor body finishes before the rest of the subclass body runs – so attributes are effectively initialised top-down. The general sequence for a single class is on page 01 (Constructors); the "with inheritance" panel of its constructor-sequence picture shows this scenario step by step.

Part 4 – Polymorphism

Polymorphism (poly = many, morph = forms): the same call behaves differently depending on the object behind the reference. A superclass (or interface) reference can point to objects of any subclass; at runtime the object's own implementation of a redefined method runs. This is dynamic binding (late binding).

Polymorphism: one table of lcl_vehicle references holding a vehicle, a cycle and a bike; the same describe( ) call runs three different implementations
  • In the Part 2 report, lt_vehicles has the static type REF TO lcl_vehicle, but the loop prints three different texts – one per class.
  • Benefit: the calling code never changes when a new subclass is added (open/closed principle). This is how BAdIs work: SAP calls an interface method, your implementation runs (Part 6).
  • Polymorphism is about objects behaving differently through one reference type – not about "a method" with several parameter lists (overloading, which ABAP does not have).

Part 5 – Abstract classes and methods

An abstract class (ABSTRACT) cannot be instantiated – it exists to be subclassed. An abstract method (METHODS m ABSTRACT) is declared but not implemented: every concrete subclass must implement it. Use it when each subclass must supply its own implementation, while shared code lives in the superclass.

CLASS lcl_shape DEFINITION ABSTRACT.
PUBLIC SECTION.
METHODS area ABSTRACT RETURNING VALUE(rv_area) TYPE decfloat34.  "no implementation
METHODS describe RETURNING VALUE(rv_text) TYPE string.           "concrete method
ENDCLASS.

CLASS lcl_shape IMPLEMENTATION.
METHOD describe.
rv_text = |Area: { area( ) }|.  "calls the subclass's area( ) at runtime
ENDMETHOD.
ENDCLASS.

CLASS lcl_circle DEFINITION INHERITING FROM lcl_shape.
PUBLIC SECTION.
METHODS constructor IMPORTING iv_radius TYPE decfloat34.
METHODS area REDEFINITION.  "implementing an abstract method = redefining it
PRIVATE SECTION.
DATA radius TYPE decfloat34.
ENDCLASS.

CLASS lcl_circle IMPLEMENTATION.
METHOD constructor.
super->constructor( ).
radius = iv_radius.
ENDMETHOD.
METHOD area.
rv_area = '3.14159' * radius * radius.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
DATA lo_shape TYPE REF TO lcl_shape.  "a reference of an abstract type is fine
lo_shape = NEW lcl_circle( 2 ).       "up cast; NEW lcl_shape( ) would be a syntax error
DATA(lv_text) = lo_shape->describe( ).
WRITE / lv_text.
  • A class with at least one abstract method must be ABSTRACT. The reverse is not required – a class can be ABSTRACT without any abstract method.
  • Abstract methods are allowed only in the PUBLIC and PROTECTED sections (private methods can't be redefined). They are also called non-concrete methods.
  • Static methods and constructors cannot be abstract – they cannot be redefined.
  • A subclass must implement (REDEFINITION) all inherited abstract methods – otherwise it must be abstract too.
  • An abstract class can have attributes, concrete methods and a constructor (called by subclasses through super->constructor( )).
  • Through an abstract-superclass reference you see only the superclass's components. To reach a subclass-only method use a down cast (Part 7); dynamic method calls are covered in Part 8.
  • ABSTRACT + FINAL together (CLASS lcl_util DEFINITION ABSTRACT FINAL.): no objects and no subclasses, so only the static components can be used – instance components can be declared but never used. This is the classic "static utility class".
    • Clean ABAP prefers objects to static classes: static methods cannot be replaced by test doubles or redefined. Use ABSTRACT FINAL only for small, stateless helpers.

How an abstract class differs from an interface, with a picture and a table, is at the end of Part 6.

Part 6 – Interfaces

An interface is a pure contract: it declares components but implements none. A class that implements the interface promises to provide all its methods. Interfaces give ABAP multiple type inheritance and are the basis of BAdIs, RAP handlers and testable code ("program to an interface").

Interfaces can contain

Interfaces cannot contain

Methods and static methods (METHODS, CLASS-METHODS), attributes (DATA, CLASS-DATA), CONSTANTS, TYPES, events (EVENTS, CLASS-EVENTS), ALIASES, other interfaces (INTERFACES)

Method implementations, visibility sections (everything is public), constructors

An interface is often called "a pure abstract class" – a useful picture, but it can hold more than abstract methods (attributes, constants, types, events), and since 7.40 SP08 methods can be optional (DEFAULT IGNORE | FAIL).

Interface implementation: two classes implement lif_printable, a class implements two interfaces, interface reference variable, intf~comp and ALIASES

Defining and implementing an interface

INTERFACE lif_printable.           "global: INTERFACE zif_printable PUBLIC.
CONSTANTS c_max_lines TYPE i VALUE 100.
METHODS print RETURNING VALUE(rv_text) TYPE string.
METHODS preview DEFAULT IGNORE.  "optional: implementing classes may skip it
ENDINTERFACE.

CLASS lcl_invoice DEFINITION.
PUBLIC SECTION.                           "INTERFACES only in the public section
INTERFACES lif_printable.
ALIASES print FOR lif_printable~print.  "short name for the interface method
ENDCLASS.

CLASS lcl_invoice IMPLEMENTATION.
METHOD lif_printable~print.  "implementation uses intf~method
rv_text = `Invoice 4711`.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
DATA lo_printable TYPE REF TO lif_printable.  "interface reference variable
lo_printable = NEW lcl_invoice( ).            "up cast: class object → interface reference
DATA(lv_text) = lo_printable->print( ).       "via the interface: no prefix

DATA(lo_invoice) = NEW lcl_invoice( ).
lv_text = lo_invoice->lif_printable~print( ).  "via the class: intf~comp
lv_text = lo_invoice->print( ).                "via the alias
DATA(lv_max) = lif_printable=>c_max_lines.     "interface constant
  • The implementing class ("implementation class") must implement all methods – except optional ones (DEFAULT IGNORE returns initial values; calling a skipped DEFAULT FAIL method raises CX_SY_DYN_CALL_ILLEGAL_METHOD) and those it declares abstract (below).
  • A class can implement any number of interfaces: INTERFACES: lif_printable, lif_storable.
  • Outside the interface, components carry the interface prefix: lif_printable~print in the class, lif_printable=>c_max_lines for constants and static components.
  • An interface cannot be instantiated: NEW lif_printable( ) is impossible – you always create an object of an implementing class and assign it to the interface reference.
  • Global classes list their interfaces on the Interfaces tab in SE24 (in ADT: the INTERFACES statement).

Nested (component) interfaces

INTERFACE lif_document.
INTERFACES lif_printable.               "lif_printable is a component interface
ALIASES print FOR lif_printable~print.  "in an interface: only for component interfaces
METHODS archive.
ENDINTERFACE.

" A class implementing lif_document implements lif_printable~print AND lif_document~archive.
" Through a lif_document reference:  lo_doc->lif_printable~print( )  or  lo_doc->print( ).
  • If an implemented interface includes other interfaces, the class must implement their methods too.
  • All component interfaces sit on one level in the implementing class: you write lif_printable~print, never lif_document~lif_printable~print.

Aliases

  • Alternative names for interface components that avoid the long intf~comp prefix: ALIASES print FOR lif_printable~print.
  • In the implementing class an alias can be declared in any visibility section; aliases declared in an interface are always public and may only point to components of its component interfaces.
  • Aliases are used only for interface components.

Partial implementation and other INTERFACES additions

Addition

Meaning

INTERFACES lif_x ABSTRACT METHODS m2.

The class leaves m2 unimplemented – the class must be ABSTRACT and a subclass implements m2 (METHODS lif_x~m2 REDEFINITION). ALL METHODS ABSTRACT for all.

METHODS m DEFAULT IGNORE | FAIL. (in the interface)

Optional method (7.40 SP08): a class need not implement it. IGNORE: calling it does nothing; FAIL: calling it raises an exception.

INTERFACES lif_x FINAL METHODS m1.

Subclasses cannot redefine m1 (ALL METHODS FINAL) – the "Final" checkbox on the SE24 Interfaces tab.

INTERFACES lif_x DATA VALUES attr = 'X'.

Start values for the interface's attributes in this class.

INTERFACES lif_x PARTIALLY IMPLEMENTED.

Only in test classes (test doubles): unimplemented methods are allowed.

Interfaces in practice: BAdIs

A BAdI (Business Add-In) is an SAP enhancement hook built entirely from the OO pieces on this page: the BAdI definition carries an interface, every BAdI implementation is a class that implements it, and SAP's code calls the interface method polymorphically – your class runs without any change to SAP's code. The full topic (enhancement spots, filters, finding BAdIs, classic BAdIs) is on CORE ABAP › 10 Enhancements, Part 5.

Mapping ABAP Objects to a new BAdI: interface = BAdI interface, implementing classes = BAdI implementations with filter values, default class = fallback class, NEW = GET BADI, polymorphic call = CALL BADI
" Global objects – in ADT each one has its own editor
INTERFACE zif_badi_tax PUBLIC.         "BAdI interface, defined with BAdI zbadi_tax
INTERFACES if_badi_interface.         "marker interface of every new BAdI
METHODS calculate CHANGING cv_tax TYPE decfloat34.
ENDINTERFACE.

CLASS zcl_tax_in DEFINITION PUBLIC FINAL CREATE PUBLIC.
PUBLIC SECTION.
INTERFACES zif_badi_tax.            "a BAdI implementation is a normal class
ENDCLASS.

CLASS zcl_tax_in IMPLEMENTATION.
METHOD zif_badi_tax~calculate.
cv_tax = cv_tax * '1.18'.
ENDMETHOD.
ENDCLASS.

" Caller (SAP's code or yours):
DATA lo_badi TYPE REF TO zbadi_tax.     "static type = the BAdI, not the interface
DATA lv_tax  TYPE decfloat34 VALUE 100.

TRY.
GET BADI lo_badi FILTERS country = 'IN'.  "framework chooses the implementation(s)
CALL BADI lo_badi->calculate CHANGING cv_tax = lv_tax.
CATCH cx_badi_not_implemented.        "single use, nothing found, no fallback class
ENDTRY.
  • GET BADI plays the role of a factory: from the active implementations and the filter values it builds the BAdI object. CALL BADI then calls the interface method – one implementation for a single-use BAdI, every matching one for a multiple-use BAdI (none found: the call is simply skipped).
  • The fallback class is the BAdI's default implementation: used only when no active implementation matches.
  • Classic BAdIs – Legacy: interface IF_EX_<name>, object from CL_EXITHANDLER=>GET_INSTANCE, then an ordinary method call. Replaced by the new BAdIs above.
  • ABAP Cloud / clean core: you implement only BAdIs that SAP has released for extensions – a stable contract that survives upgrades.

Abstract class vs interface

Abstract class lcl_shape with concrete describe and abstract area, inherited by lcl_circle and lcl_square; interface lif_printable implemented by unrelated classes lcl_invoice, lcl_employee and lcl_circle

Abstract class

Interface

Methods

Abstract and concrete methods; ABSTRACT must be written explicitly

Only declarations – all methods are "abstract" by default (optional DEFAULT IGNORE | FAIL)

Visibility

Public, protected, private sections; abstract methods public or protected

No sections – all components public

Attributes, constructor

Any attributes; can have a constructor

Attributes and constants; no constructor

How many per class

One superclass

Any number of interfaces

Access in subclass / class

Inherited components used directly

With prefix intf~comp or an alias

Use when

Subclasses share code and state ("is-a" with common implementation)

Unrelated classes must offer the same behaviour (contract, BAdI, test double)

Part 7 – Casting: up cast and down cast

Every reference variable has a static type (the type in its declaration – it decides which components you may address) and a dynamic type (the class of the object it points to at runtime – it decides which implementation runs). Casting assigns references between related types.

Up cast from subclass to superclass or interface (always allowed with =), down cast from superclass to subclass with ?= or CAST, checked at runtime, CX_SY_MOVE_CAST_ERROR

SAP's current term

Old SAP term

Direction

Operator

Check

Up cast

narrowing cast

Subclass → superclass, class → interface

=

Compile time – always safe

Down cast

widening cast

Superclass / interface → subclass or class

?= or CAST

Runtime – fails with CX_SY_MOVE_CAST_ERROR if the object is not of that type

Terminology – the most important point: SAP called the up cast a narrowing cast (the view narrows to fewer components) and the down cast a widening cast; many blogs mix these names up. SAP documentation now uses only up cast / down cast – use those terms.

Up cast

DATA lo_vehicle   TYPE REF TO lcl_vehicle.
DATA lo_printable TYPE REF TO lif_printable.

lo_vehicle   = NEW lcl_bike( iv_color = `black` iv_gears = 21 ).  "sub → super
lo_printable = NEW lcl_invoice( ).        "class → interface
DATA(lv_text) = lo_vehicle->describe( ).  "runs lcl_bike's redefinition (dynamic binding)
" lo_vehicle->gears                       "syntax error: gears is unknown to the static type
  • After an up cast only components known to the static type can be addressed – components that exist only in the subclass are not accessible through the superclass reference; but a redefined method still runs the subclass implementation.

Down cast

DATA lo_bike TYPE REF TO lcl_bike.

lo_bike ?= lo_vehicle.                         "classic down cast operator
lo_bike = CAST #( lo_vehicle ).                "CAST operator (7.40)
DATA(lo_bike2) = CAST lcl_bike( lo_vehicle ).  "with explicit type, inline
DATA(lv_gears_text) = CAST lcl_bike( lo_vehicle )->describe( ).  "cast and call in one go

TRY.
lo_bike ?= NEW lcl_vehicle( 4 ).        "object is NOT a bike
CATCH cx_sy_move_cast_error INTO DATA(lx_cast).
MESSAGE lx_cast->get_text( ) TYPE 'I'.  "no short dump
ENDTRY.
  • A down cast succeeds only if the object really is of the target class (or one of its subclasses) – typically after an earlier up cast. A pure superclass object can never be down cast to a subclass.
  • Check before casting (7.50) instead of catching the exception:
IF lo_vehicle IS INSTANCE OF lcl_bike.
lo_bike = CAST #( lo_vehicle ).
ENDIF.

CASE TYPE OF lo_vehicle.  "most specific class first
WHEN TYPE lcl_bike  INTO DATA(lo_b).  WRITE / 'Bike'.
WHEN TYPE lcl_cycle INTO DATA(lo_c).  WRITE / 'Cycle'.
WHEN OTHERS.                          WRITE / 'Other vehicle'.
ENDCASE.
  • MOVE lo_vehicle ?TO lo_bike. is the obsolete long form – use ?= or CAST.
  • Interfaces work the same way: lo_invoice = CAST #( lo_printable ). is a down cast from interface to class.

Generic object references: REF TO object

Every class inherits from the root class OBJECT, so a variable TYPE REF TO object can hold any object – assigning to it is always an up cast. The price: the static type OBJECT has no components, so nothing can be called through it directly.

DATA lo_any TYPE REF TO object.

lo_any = NEW lcl_bike( iv_color = `red` iv_gears = 7 ).  "up cast to the root class
" lo_any->describe( )                                    "syntax error: OBJECT has no methods

IF lo_any IS INSTANCE OF lcl_vehicle.                    "check, then down cast
DATA(lv_text) = CAST lcl_vehicle( lo_any )->describe( ).
ENDIF.

" ... or a dynamic call (Part 8):
CALL METHOD lo_any->('DESCRIBE') RECEIVING rv_text = lv_text.
  • Use it where code must accept objects of unrelated classes (generic containers, frameworks). Otherwise prefer an interface type – the compiler can then check the calls.
  • TYPE REF TO data is the counterpart for data objects; both kinds are compared on page 01.

Part 8 – Dynamic method calls

The method (and even the class) name is in a variable and resolved at runtime. It is sometimes used to reach subclass methods through a superclass reference.

DATA(lv_method) = `DESCRIBE`.         "names in upper case
CALL METHOD lo_vehicle->(lv_method) RECEIVING rv_text = lv_text.  "instance method
CALL METHOD (lv_class)=>(lv_method).  "static method, class at runtime
CALL METHOD lo_vehicle->(lv_method) PARAMETER-TABLE lt_params.  "parameters built at runtime

TRY.
CALL METHOD lo_vehicle->('SETBIKE').
CATCH cx_sy_dyn_call_illegal_method.  "method unknown or not visible
ENDTRY.
  • The method is searched in the static type and then in the dynamic type of the object – that is why it can reach subclass-only methods. But there is no syntax check: typos and wrong parameters only show up at runtime (CX_SY_DYN_CALL_ILLEGAL_METHOD, CX_SY_DYN_CALL_PARAM_MISSING …).
Dynamic method call: name in a variable, CALL METHOD oref->(name), lookup in the static then the dynamic type at runtime, method runs or CX_SY_DYN_CALL_ILLEGAL_METHOD is raised
  • Better: a down cast (Part 7) – or, as a design fix, declare the method in the superclass or an interface so a normal polymorphic call works. Use dynamic calls only for genuinely generic frameworks.
  • ABAP Cloud: only released SAP classes and methods may be used. A dynamic name is not checked by the compiler, so a call to an unreleased SAP object is not caught at compile time – expect an error at runtime instead. CL_ABAP_DYN_PRG helps to validate names that come from outside.
  • Clean ABAP: write normal (functional) calls and keep CALL METHOD for dynamic calls, where it is still required.

Part 9 – UML notation

UML class diagrams show classes, interfaces and their relationships. You will see them in design documents and interviews.

UML class diagram: interface ZIF_HR, abstract class ZCL_HR, subclasses ZCL_HR_EMP, ZCL_HR_ORG_UNIT, ZCL_HR_POSITION, composition with ZCL_HR_PERSON and ZCL_USER

Symbol

Meaning

In the diagram

Box with 3 compartments

Class name / attributes / methods

ZCL_HR_EMP: -PERSON, -USER; +GET_PERSON( ) …

<<interface>>

Interface

ZIF_HR with +GET_MANAGER( ) …

Class name in italics

Abstract class

ZCL_HR

+ / # / -

Public / protected / private

-PLVAR (private attribute), +GET( ) (public method)

Solid line, hollow triangle

Inheritance ("is-a")

ZCL_HR_EMP, ZCL_HR_ORG_UNIT, ZCL_HR_POSITION inherit from ZCL_HR; ZCL_HR_MGR and ZCL_HR_ASST from ZCL_HR_EMP

Dashed line, hollow triangle

Interface realisation (INTERFACES)

The HR classes implement ZIF_HR

Filled diamond

Composition ("has-a", the part lives with the whole)

ZCL_HR_EMP has a ZCL_HR_PERSON and a ZCL_USER

Composition over inheritance: inherit only for a true "is-a" relationship; otherwise hold a reference to another object ("has-a") and delegate to it – looser coupling, easier to test.

Part 10 – Interview questions

Does ABAP support multiple inheritance?

Not for classes: every class has exactly one superclass (root class OBJECT). A class can implement any number of interfaces, which gives multiple type inheritance – the class must still implement the methods itself.

Are private components inherited?

Yes, they exist in every subclass object and the superclass's methods use them, but they are not visible in the subclass. Only public and protected components can be addressed there.

Overloading vs overriding – which does ABAP support?

Only overriding (redefinition): a subclass re-declares an inherited instance method with REDEFINITION and implements it again, same signature. Overloading – one name, several parameter lists – is not supported; use optional parameters or different method names.

What are the rules for redefining a method?

Only public or protected, non-final instance methods; the signature, visibility and category stay the same; static, private, final methods and constructors cannot be redefined. super->m( ) calls the superclass version inside the redefinition. A redefinition can be made FINAL.

Why must a subclass constructor call super->constructor( )?

So the inherited part of the object is initialised by the superclass's own logic. It is mandatory whenever the subclass declares its own instance constructor, and before the call the subclass cannot use instance attributes. A subclass without its own constructor uses the superclass constructor and its parameters.

Abstract class vs interface – when do you use which?

An abstract class can hold concrete code, attributes, a constructor and protected components; a class inherits only one. An interface is a pure contract with public components only; a class can implement many. Use an abstract class for shared implementation in an is-a hierarchy, an interface for a contract that unrelated classes fulfil (BAdIs, test doubles).

Can you instantiate an abstract class? Must it have abstract methods?

No – NEW on an abstract class is a syntax error, but you can declare references of its type and create objects of concrete subclasses. An abstract class does not need abstract methods; a class that has an abstract method must be abstract.

Explain up cast and down cast. What are narrowing and widening casts?

Up cast: subclass or class reference to superclass or interface reference, always allowed with = (old name narrowing cast). Down cast: back to the more specific type with ?= or CAST, checked at runtime (old name widening cast); if the object is not of that type, CX_SY_MOVE_CAST_ERROR is raised. Check first with IS INSTANCE OF or CASE TYPE OF.

What is polymorphism / dynamic binding? Give an example.

One reference type, many behaviours: a superclass or interface reference points to objects of different classes, and calling a redefined method runs each object's own implementation. Example: a table of REF TO lcl_vehicle holding cycles and bikes – the same describe( ) call prints different texts. BAdIs rely on it.

How do you call a method of a nested interface? What are aliases?

Component interfaces are on one level: in the class you write lif_inner~m, and through a reference to the outer interface lo->lif_inner~m( ). An alias (ALIASES m FOR lif_inner~m) gives an interface component a short name in the class or the outer interface.

Can a class implement only part of an interface?

Yes: with INTERFACES lif_x ABSTRACT METHODS m (the class becomes abstract, a subclass implements m), or if the interface declares the method DEFAULT IGNORE or DEFAULT FAIL (7.40 SP08). PARTIALLY IMPLEMENTED is allowed only in test classes.

FINAL class vs FINAL method?

A FINAL class cannot have subclasses. A FINAL method is inherited but cannot be redefined; it makes sense only for public or protected instance methods, because static and private methods can't be redefined anyway.

What is a class that is both ABSTRACT and FINAL?

It can have neither objects nor subclasses, so only its static components can be used – a static utility class. Instance components may be declared but can never be used. Clean ABAP prefers objects to static classes because static methods cannot be replaced by test doubles.

How is a BAdI related to interfaces and polymorphism?

A new BAdI defines an interface (including IF_BADI_INTERFACE); each implementation is a class that implements it. GET BADI picks the active implementations by filter values (or the fallback class), and CALL BADI calls the interface method – SAP's code knows only the interface, the implementing class decides what runs. Classic BAdIs use CL_EXITHANDLER=>GET_INSTANCE and are legacy; in ABAP Cloud only released BAdIs can be implemented.

ABAP has no overloading – how can one method accept values of different types?

With generic typing: IMPORTING iv_value TYPE simple (or any, data, numeric, clike, ANY TABLE …). The actual type comes from the argument at runtime. A RETURNING parameter must be completely typed; REF TO data and REF TO object count as complete.

What can you do with a variable of TYPE REF TO object?

It can hold any object, because every class inherits from OBJECT. But OBJECT has no components, so to use the object you down cast it (after IS INSTANCE OF or with CASE TYPE OF) or call a method dynamically. Prefer an interface type when the methods are known.

🏠 Start Here · ◀ 01 · Classes & Objects · 03 · Exceptions & Events ▶ · 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