Skip to content

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

ABAP Objects, Inheritance

This example demonstrates how a counter is specialized using inheritance.

Other versions: 7.31 | 7.40 | 7.54

Source Code

REPORT demo_inheritance.

CLASS counter DEFINITION.
  PUBLIC SECTION.
    METHODS:
      set
        IMPORTING value(set_value) TYPE i,
      increment,
      get
        EXPORTING value(get_value) TYPE i.
  PROTECTED SECTION.
    DATA count TYPE i.
ENDCLASS.

CLASS counter IMPLEMENTATION.
  METHOD set.
    count = set_value.
  ENDMETHOD.
  METHOD increment.
   count += 1.
  ENDMETHOD.
  METHOD get.
    get_value = count.
  ENDMETHOD.
ENDCLASS.

CLASS counter_ten DEFINITION INHERITING FROM counter.
  PUBLIC SECTION.
    METHODS increment REDEFINITION.
    DATA count_ten TYPE c LENGTH 1.
ENDCLASS.

CLASS counter_ten IMPLEMENTATION.
  METHOD increment.
    DATA modulo TYPE i.
    super->increment( ).
    modulo = count MOD 10.
    IF modulo = 0.
      count_ten += 1.
      cl_demo_output=>write_text( |{ count } - { count_ten }| ).
    ELSE.
      cl_demo_output=>write_text( |{ count }| ).
    ENDIF.
  ENDMETHOD.
ENDCLASS.

DATA: count TYPE REF TO counter,
      number TYPE i VALUE 5.

START-OF-SELECTION.

  count = NEW counter_ten( ).

  count->set( number ).

  DO 20 TIMES.
    count->increment( ).
  ENDDO.
  cl_demo_output=>display( ).

Description

The class counter_ten is derived from counter and redefines the method increment. In counter, the visibility of the attribute count must be changed from PRIVATE to PROTECTED. In the redefined method, the obscured method with the pseudo reference super-> is called. The redefined method specializes the inherited method.

An object of the subclass is created to which a reference variable of the superclass type points. When the method increment is executed, the redefined method of the subclass is executed using the superclass reference.