Interfaces, Inheritance and Polymorphism
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A program often has to do the same job in several ways. An expense claim, for example, is paid out in full, or only up to a limit, or after a deduction, and the code that processes claims should not have to know which way applies. ABAP Objects solves this with two tools. An interface is a list of methods that a class promises to offer, without saying how. An inheritance relationship lets a new class start from an existing one and change only the parts that differ. Both let the caller treat many different objects as if they were one kind of thing, which is called polymorphism. This page explains interfaces, aliases, inheritance, abstract classes, redefinition and the casts between reference types, and builds one small example, payout strategies, that you can run. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). The language elements on this page are part of ABAP Objects and behave the same in ABAP Cloud, in classic Standard ABAP, on premise and in the Public Edition. The runnable example is a report with local classes, a form that classic Standard ABAP allows and ABAP Cloud does not (ABAP Cloud has no reports); the section on global declarations shows the form you write there.
Before you read
-
Data Types and Data Objects: types, constants and inline declarations.
-
Constructor Expressions:
NEWcreates an object andVALUEbuilds a table; this page also usesCAST. -
Internal Tables: the example keeps its objects in a table.
-
Classes and Objects, the page before this one in the ABAP Objects part of the section, explains attributes, methods, visibility sections and constructors; this page repeats only what it needs.
Key terms
-
Interface: a named list of components, mostly methods, that classes can implement; it has no instances of its own.
-
Interface reference: a variable typed
TYPE REF TOan interface that can point to an object of any class implementing that interface. -
Alias: a short second name for a component of an implemented interface.
-
Inheritance: deriving a subclass from a superclass so that the subclass has all the visible components of the superclass.
-
Abstract class: a class that cannot be instantiated and may leave methods without an implementation for its subclasses to supply.
-
Redefinition: giving an inherited method a new implementation in a subclass, with the same name and parameters.
-
Polymorphism: the same call running different code depending on the class of the object behind the reference.
-
Downcast: assigning a reference to a more specific type, which must be written explicitly and is checked when the program runs.
The example used on this page
The expense claims of the running example are paid out by a payout strategy. One strategy pays the claimed amount in full. Another pays at most a fixed cap. The code that handles a claim only wants to say "calculate the payout for 350" and get an amount back, whichever strategy is in force. The plan is therefore:
-
an interface
lif_payoutthat describes what every strategy can do, -
an abstract class
lcl_payout_basethat holds what all strategies share, -
two subclasses,
lcl_full_payoutandlcl_capped_payout, that each calculate in their own way.
The names start with lif_ and lcl_ because they are local interfaces and classes, declared inside the program; the
global ones you create in a package start with zif_ and zcl_.
Interfaces
An interface is declared between INTERFACE and ENDINTERFACE. It can contain the same kinds of components as a class
(methods, attributes, constants, types and events), but no implementations, and it cannot be instantiated. A class that
wants to offer what the interface describes writes INTERFACES <name> in its public section and then provides an
implementation for each method. After that, every component of the interface is a full component of the class, and its
name is the interface name, a tilde ~ and the component name, for example lif_payout~calculate.
Interfaces solve one problem in particular. Different classes that implement the same interface offer the same methods,
so a variable typed TYPE REF TO lif_payout can point to an object of any of them. The caller works with the interface
and never mentions a class. The Keyword Documentation recommends calling through the interface reference rather than
through a class reference, and says that interface references are, next to inheritance, the basis for polymorphism.
Three details are worth knowing early.
-
Constants are the one static component you reach through the interface name, as in
lif_payout=>min_amount. All other static components are reached through an implementing class. -
A class can implement any number of interfaces, but it can have only one direct superclass. The Keyword Documentation adds that each interface can be implemented only once along one inheritance tree.
-
An interface can include other interfaces with
INTERFACESinside its own definition. The interface that includes is called a nested interface and every component of an included interface becomes a component of the nested one. A reference typed with the nested interface can be assigned to a reference typed with an included interface.
The first part of the example declares the interface. Method parameters cannot carry a length or decimals, so the interface
declares a type ty_amount for the amounts and uses it for the parameters. This listing is the first of four that together
form one report; the four run in the local playground as shown at the end of the example.
REPORT zp_ifc.
INTERFACE lif_payout.
TYPES ty_amount TYPE p LENGTH 8 DECIMALS 2.
CONSTANTS min_amount TYPE ty_amount VALUE '1.00'.
METHODS calculate
IMPORTING claimed TYPE lif_payout=>ty_amount
RETURNING VALUE(payout) TYPE lif_payout=>ty_amount.
METHODS describe
RETURNING VALUE(text) TYPE string.
ENDINTERFACE.
Implementing an interface and aliases
The statement INTERFACES in the public section of a class implements an interface. It has additions for adapting the
interface to the class. ABSTRACT METHODS leaves a method without an implementation in this class, FINAL METHODS forbids
subclasses to redefine it, and DATA VALUES sets start values for attributes of the interface. A method that the interface
declares with the addition DEFAULT does not have to be implemented at all; it then falls back on the default behaviour
the interface defines.
Writing lif_payout~calculate everywhere is long. The statement ALIASES alias FOR intf~comp gives a component of an
implemented interface a second, shorter name. The alias is a component of the class in its own right, lives in the same
namespace as the other components and is inherited by subclasses, so base->calculate( ... ) works through a class
reference as well. You can use the alias or the full name when you implement the method and when you redefine it. The
syntax check warns when one context uses both names for the same component, so pick one per class.
The next listing shows the second part of the example. The abstract class lcl_payout_base implements the interface, leaves
calculate abstract with ABSTRACT METHODS, supplies a shared implementation of describe and declares the alias. A
class that implements an interface must implement every method that is not abstract, and the base class does that for
describe only. It also declares one method of its own, describe_policy.
CLASS lcl_payout_base DEFINITION ABSTRACT.
PUBLIC SECTION.
INTERFACES lif_payout ABSTRACT METHODS calculate.
ALIASES calculate FOR lif_payout~calculate.
METHODS describe_policy
RETURNING VALUE(text) TYPE string.
ENDCLASS.
CLASS lcl_payout_base IMPLEMENTATION.
METHOD lif_payout~describe.
text = |policy with minimum { lif_payout=>min_amount }|.
ENDMETHOD.
METHOD describe_policy.
text = lif_payout~describe( ).
ENDMETHOD.
ENDCLASS.
Inheritance
Inheritance builds a new class from an existing one. The addition INHERITING FROM of CLASS ... DEFINITION names the
existing class, the superclass, and the new class, the subclass, starts with all the components of the superclass that it
can see. The subclass then adds components of its own or changes inherited methods, which makes it more specialised. ABAP
Objects has single inheritance: a class has at most one direct superclass, while a superclass can have many subclasses.
Together the classes form a tree whose root is the predefined empty class object; you never name it yourself.
Visibility does not change through inheritance. A subclass sees the public and protected components of its superclasses (and the package-visible ones in the same package). The private components of a superclass exist in every subclass object but cannot be seen or used there. A subclass may declare a private component with the same name; each class then works with its own.
Constructors follow special rules, because an object of a subclass is also an object of every superclass above it.
The instance constructor of a subclass must call super->constructor before it uses me or any instance component. If
the superclass has no explicit constructor, the call still has to appear when the subclass defines its own, and no parameters
are passed. A constructor cannot be redefined, and the constructors of a tree are independent of one another.
Because inheritance fixes the structure early and ties the subclass to the details of the superclass, designs that use it
need care. The Clean ABAP style guide says to avoid hierarchies of classes and to prefer composition, and to declare a
class FINAL unless it is designed for inheritance. A final class cannot have subclasses, and a final method cannot be
redefined.
Abstract classes and redefinition
A class declared with ABSTRACT cannot be instantiated: NEW lcl_payout_base( ) is a syntax error. It exists to be
inherited from. An abstract method (METHODS ... ABSTRACT, or ABSTRACT METHODS on an INTERFACES line, as above) has no
implementation in that class; a subclass must supply it before the subclass can be instantiated. Concrete methods of the
abstract class may already call the abstract ones, which is the main use: the base class fixes the order of the steps and
the subclasses fill in the steps.
To change an inherited public or protected instance method in a subclass, you declare it again with the addition
REDEFINITION and write a new implementation. The name and the parameters stay as they are; only the code changes. The
declaration and the original implementation remain in the superclass, and inside the redefined method you can reach the
hidden implementation with super->method( ), for example to add a text to what the superclass returns. A redefined
method uses the private attributes of the subclass, and private methods cannot be redefined at all. An interface method
is redefined the same way, using the interface name with the tilde, or an alias.
Every reference that points to a subclass object runs the redefined method, even when the reference was typed with the
superclass. This holds for the self-reference me as well: when a base-class method calls another method on me, and a
subclass redefines that method, the subclass version runs for a subclass object. The one exception is inside a constructor,
where a call on me runs the version of the class whose constructor is running, because the subclass part of the object is
not built yet.
The third part of the example completes the report. The class lcl_full_payout pays the claimed amount. The class
lcl_capped_payout has a constructor that takes the cap, calls super->constructor first, and redefines calculate
and describe. In describe it calls the hidden version with super->lif_payout~describe and adds the cap to the text.
CLASS lcl_full_payout DEFINITION INHERITING FROM lcl_payout_base.
PUBLIC SECTION.
METHODS lif_payout~calculate REDEFINITION.
ENDCLASS.
CLASS lcl_full_payout IMPLEMENTATION.
METHOD lif_payout~calculate.
payout = claimed.
ENDMETHOD.
ENDCLASS.
CLASS lcl_capped_payout DEFINITION INHERITING FROM lcl_payout_base.
PUBLIC SECTION.
METHODS constructor IMPORTING cap TYPE lif_payout=>ty_amount.
METHODS lif_payout~calculate REDEFINITION.
METHODS lif_payout~describe REDEFINITION.
PRIVATE SECTION.
DATA cap TYPE lif_payout=>ty_amount.
ENDCLASS.
CLASS lcl_capped_payout IMPLEMENTATION.
METHOD constructor.
super->constructor( ).
me->cap = cap.
ENDMETHOD.
METHOD lif_payout~calculate.
payout = nmin( val1 = claimed val2 = cap ).
ENDMETHOD.
METHOD lif_payout~describe.
text = |{ super->lif_payout~describe( ) }, capped at { cap }|.
ENDMETHOD.
ENDCLASS.
Polymorphism
Polymorphism means that one call can run different code. A reference typed with a superclass, or with an interface that a
superclass implements, may hold an object of any subclass, because a subclass has all components of its superclass and the
parameters of a method never change. The static type of the reference decides which components you can name. Which
implementation runs is decided at runtime by the class of the object. Here the interface reference calls calculate and the
payout depends only on the object.
The diagram reads from the top. The dotted arrow means "implements" and the solid arrow means "inherits from". A call to
calculate through a lif_payout reference ends in one of the two subclasses.
Casting between reference types
Assigning a reference of a subclass type to a reference of a superclass or interface type is always safe and needs nothing
special. It is called an upcast, and it is what iface = full does in the example below. The opposite direction, a
downcast, assigns from a general type to a more specific one. The compiler cannot know which object is behind the
reference, so you must write the downcast explicitly, and the system checks it when the program runs. There are two forms.
-
The assignment operator
?=, as incapped ?= base., moves the reference if the object is of the target type and otherwise raises the exceptioncx_sy_move_cast_error. -
The constructor expression
CAST, as inCAST lcl_capped_payout( base ), does the same inside an expression and avoids a helper variable.CASTalso works for an explicit upcast. When a plainCASTis written as a statement on its own, it only tests whether the cast would work.
To test before you cast, use the predicate expression IS INSTANCE OF, as in base IS INSTANCE OF lcl_full_payout, or a
CASE TYPE OF distinction with WHEN TYPE. A cast that is not guarded and fails raises the catchable exception
cx_sy_move_cast_error, so wrap risky casts in TRY and CATCH, which the page on class-based exceptions covers.
The report body below uses everything built so far. It puts one strategy of each kind into a table typed with the interface,
loops over it, then shows the alias, the two downcast forms, the IS INSTANCE OF test, a failing cast that is caught, and an
upcast to the interface.
START-OF-SELECTION.
DATA strategies TYPE STANDARD TABLE OF REF TO lif_payout WITH EMPTY KEY.
strategies = VALUE #( ( NEW lcl_full_payout( ) ) ( NEW lcl_capped_payout( 200 ) ) ).
LOOP AT strategies INTO DATA(strategy).
WRITE / |{ strategy->describe( ) }: { strategy->calculate( 350 ) }|.
ENDLOOP.
" alias: the short name works through the class reference
DATA full TYPE REF TO lcl_full_payout.
full = NEW #( ).
WRITE / |alias: { full->calculate( 80 ) }|.
WRITE / |own method: { full->describe_policy( ) }|.
" casting
DATA base TYPE REF TO lcl_payout_base.
base = NEW lcl_capped_payout( 50 ).
DATA capped TYPE REF TO lcl_capped_payout.
capped ?= base.
WRITE / |down cast with ?=: { capped->calculate( 100 ) }|.
DATA(again) = CAST lcl_capped_payout( base ).
WRITE / |down cast with CAST: { again->calculate( 10 ) }|.
IF base IS INSTANCE OF lcl_full_payout.
WRITE / 'base is a full payout'.
ELSE.
WRITE / 'base is not a full payout'.
ENDIF.
TRY.
DATA wrong TYPE REF TO lcl_full_payout.
wrong ?= base.
CATCH cx_sy_move_cast_error.
WRITE / 'wrong cast caught: cx_sy_move_cast_error'.
ENDTRY.
DATA iface TYPE REF TO lif_payout.
iface = full.
WRITE / |interface reference: { iface->calculate( 5 ) }|.
The four listings above, joined in the order shown into one report, run in the local playground and print:
policy with minimum 1.00: 350.00 policy with minimum 1.00, capped at 200.00: 200.00 alias: 80.00 own method: policy with minimum 1.00 down cast with ?=: 50.00 down cast with CAST: 10.00 base is not a full payout wrong cast caught: cx_sy_move_cast_error interface reference: 5.00
The first two lines are polymorphism at work: the same call strategy->calculate( 350 ) returns 350.00 for the full payout and
200.00 for the capped one, and describe shows the redefined text only for the capped one. The order matters: the interface, the abstract class and the
two subclasses are declared before START-OF-SELECTION, because a class must be declared before the code that uses it.
Global interfaces and classes, and ABAP Cloud
In a real project the interface and the classes are not local to a report. You create each one in a package, as a global
interface or global class with a name starting with zif_ or zcl_, in the ABAP development tools in Eclipse. Their
declarations use exactly the statements above. The listing shows a global interface and a final class that implements it,
which is how the capped strategy would look in a package. In ABAP Cloud a program reaches such code through classes and
interfaces like these, since reports are not available there. It requires an SAP system; not run here.
INTERFACE zif_exp_payout PUBLIC.
TYPES ty_amount TYPE p LENGTH 8 DECIMALS 2.
METHODS calculate
IMPORTING claimed TYPE zif_exp_payout=>ty_amount
RETURNING VALUE(payout) TYPE zif_exp_payout=>ty_amount.
ENDINTERFACE.
CLASS zcl_exp_capped_payout DEFINITION PUBLIC FINAL CREATE PUBLIC.
PUBLIC SECTION.
INTERFACES zif_exp_payout.
ALIASES calculate FOR zif_exp_payout~calculate.
METHODS constructor IMPORTING cap TYPE zif_exp_payout=>ty_amount.
PRIVATE SECTION.
DATA cap TYPE zif_exp_payout=>ty_amount.
ENDCLASS.
CLASS zcl_exp_capped_payout IMPLEMENTATION.
METHOD constructor.
me->cap = cap.
ENDMETHOD.
METHOD zif_exp_payout~calculate.
payout = nmin( val1 = claimed val2 = cap ).
ENDMETHOD.
ENDCLASS.
A caller in another class then declares DATA payout TYPE REF TO zif_exp_payout, creates the object with NEW, and never
names the class again. That is the form that is easy to replace with a test double in a unit test, which the page on design patterns picks up again with the strategy pattern.
Interface or inheritance
Use an interface when different classes only have to offer the same methods and may otherwise be unrelated. Use inheritance when a subclass really is a specialised version of its superclass and shares most of its behaviour, so that only a few methods are redefined. Many designs combine them, as the example does: the interface defines what a strategy is, the base class holds what all strategies share, and callers see only the interface. When in doubt, the Clean ABAP style guide suggests that public instance methods belong to an interface and that composition is preferred to inheritance.
Older ABAP code and older books show the same ideas with a different surface. Programs written before release 7.40 create
objects with CREATE OBJECT and call methods with CALL METHOD, and declare every helper variable at the top. The statements
and rules on this page have not changed since, but new code uses NEW, functional calls and CAST, as above. The books
consulted for this page, Complete ABAP (its first edition targets AS ABAP 7.4 and 7.5, so it predates ABAP Cloud) and Keller
and Krüger’s ABAP Objects (2002, so it predates inline declarations and NEW), teach the same object model; where they differ
in syntax, follow the Keyword Documentation.
Summary
-
An interface lists methods a class promises to offer. A class implements it with
INTERFACESin its public section and reaches its components asintf~comp;ALIASESgives a component a shorter name that subclasses inherit. -
A reference typed with an interface can point to any object whose class implements it, and calling through it runs the implementation of that class. That is polymorphism, and it works for inheritance in the same way.
-
INHERITING FROMmakes a subclass that sees the public and protected components of its single direct superclass. The subclass constructor must callsuper->constructorfirst. -
An abstract class cannot be instantiated and may leave methods abstract;
REDEFINITIONreplaces an inherited method with the same interface, andsuper->reaches the hidden version.FINALforbids further redefinition or inheritance. -
An upcast is implicit. A downcast is written with
?=orCAST, fails at runtime withcx_sy_move_cast_errorwhen the object is of another type, and can be tested first withIS INSTANCE OF. -
Prefer interfaces and composition, and keep inheritance for classes designed for it.
Try it
To do this by hand, follow the guide Classes, Interfaces and Exceptions: it builds a claim validator class, a payout interface and an exception class.
References
-
ABAP Keyword Documentation: ABAP Objects, Nesting Interfaces
-
ABAP Keyword Documentation: ABAP Objects, Inheritance and Constructors
-
ABAP Keyword Documentation: ABAP Objects, Abstract and Final Methods and Classes
-
ABAP Keyword Documentation: ABAP Objects, Redefining Methods
-
ABAP Keyword Documentation: ABAP Objects, Inheritance and Polymorphism
-
ABAP Keyword Documentation: ABAP Objects, Inheritance and Interfaces
-
ABAP Keyword Documentation: Predicate Expression IS INSTANCE OF
-
Complete ABAP (SAP PRESS), Kiran Bandari; the copy consulted is the 1st edition