Skip to content

ABAP Keyword Documentation →  ABAP − Reference →  Declarations →  Declaration Statements →  Classes and Interfaces →  ABAP Objects - Overview →  Examples for ABAP Objects 

ABAP Objects, Interfaces

This example demonstrates the use of interfaces.

Other versions: 7.31 | 7.40 | 7.54

Source Code

REPORT demo_interface.

INTERFACE status.
  METHODS write.
ENDINTERFACE.

CLASS counter DEFINITION.
  PUBLIC SECTION.
    INTERFACES status.
    METHODS increment.
  PRIVATE SECTION.
    DATA count TYPE i.
ENDCLASS.

CLASS counter IMPLEMENTATION.
  METHOD status~write.
    cl_demo_output=>write_text( |Count in counter is { count }| ).
  ENDMETHOD.
  METHOD increment.
    count += 1.
  ENDMETHOD.
ENDCLASS.

CLASS bicycle DEFINITION.
  PUBLIC SECTION.
    INTERFACES status.
    METHODS drive.
  PRIVATE SECTION.
    DATA speed TYPE i.
ENDCLASS.

CLASS bicycle IMPLEMENTATION.
  METHOD status~write.
    cl_demo_output=>write_text( |Speed of bicycle is { speed }| ).
  ENDMETHOD.
  METHOD drive.
    speed += 10.
  ENDMETHOD.
ENDCLASS.

DATA status_tab TYPE TABLE OF REF TO status WITH EMPTY KEY.

START-OF-SELECTION.

  DATA(count) = NEW counter( ).
  DATA(bike) =  NEW bicycle( ).

  DO 5 TIMES.
    count->increment( ).
    bike->drive( ).
  ENDDO.

  status_tab = VALUE #( ( count )
                        ( bike ) ).

  LOOP AT status_tab ASSIGNING FIELD-SYMBOL(<status>).
    <status>->write( ).
  ENDLOOP.
  cl_demo_output=>display( ).

Description

This example shows an interface status for displaying the attributes of an object and its implementation in two different classes.

The interface status contains a method write. The classes counter and bicycle implement the interface in the public area. Both classes must implement the interface method in the implementation part in accordance with the required semantics.

First, two class reference variables are declared, count and bike, for the classes counter and bicycle. An interface reference variable status and an internal table status_tab with a suitable row type for the interface reference variable are created for the interface status. All the reference variables begin with initial values.

Using the constructor operator NEW, an object is created for each class to which the references in count and bike point. Using the class reference variable, the methods increment and drive are called in the respective objects.

Class reference variables are inserted in the interface reference table to make the rows in status_tab point to the two objects as well. Using the interface references, it is possible to call the interface method write in the objects, but not the class methods increment or drive.