Show TOC

Inheritance: Introductory ExampleLocate this document in the navigation structure

The following simple example shows the principle of inheritance within ABAP Objects. It is based on the Simple Introduction to Classes . A new class counter_ten inherits from the existing class counter.

Tip

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.    ADD 1 TO count.  ENDMETHOD.  METHOD get.    get_value = count.  ENDMETHOD.ENDCLASS.

CLASS counter_ten DEFINITION INHERITING FROM counter.PUBLIC SECTION.    METHODS increment REDEFINITION.    DATA count_ten.ENDCLASS.

CLASS counter_ten IMPLEMENTATION.  METHOD increment.    DATA modulo TYPE i.    CALL METHOD super->increment.    write / count.    modulo = count mod 10.    IF modulo = 0.      count_ten = count_ten + 1.      write count_ten.    ENDIF.  ENDMETHOD.ENDCLASS.

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

START-OF-SELECTION.

 CREATE OBJECT count TYPE counter_ten.

 CALL METHOD count->set EXPORTING set_value = number.

 DO 20 TIMES.    CALL METHOD count->increment.  ENDDO.

The class counter_ten is derived from counter. It redefines the method increment. To do this, you must change the visibility of the count attribute from PRIVATE to PROTECTED. The redefined method calls the obscured method of the superclass using the pseudoreference super->. The redefined method is a specialization of the inherited method.

The example instantiates the subclass. The reference variable pointing to it has the type of the superclass. When the INCREMENT method is called using the superclass reference, the system executes the redefined method from the subclass.