Skip to content

ABAP Keyword Documentation →  ABAP - Reference →  Declarative statemnts →  Classes and Interfaces →  ABAP Objects - Overview →  Examples for ABAP Objects 

ABAP Objects, Inheritance

This example demonstrates the specialization of a counter 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.
    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 TYPE c LENGTH 1.
ENDCLASS.

CLASS counter_ten IMPLEMENTATION.
  METHOD increment.
    DATA modulo TYPE i.
    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.

  count->set( number ).

  DO 20 TIMES.
    count->increment( ).
  ENDDO.

Description

The counter_ten class is derived from counter and redefines the increment method. In counter, the visibility of the attribute count must be changed from PRIVATE to PROTECTED. In the redefined method, the nested 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. During the execution of the increment method, the redefined method of the subclass is executed using the superclass reference.