Skip to content

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

ABAP Objects, Classes

This example demonstrates a class for counters.

Other versions: 7.31 | 7.40 | 7.54

Source Code

REPORT demo_class_counter .

CLASS counter DEFINITION.
  PUBLIC SECTION.
    METHODS: set
               IMPORTING value(set_value) TYPE i,
             increment,
             get
               EXPORTING value(get_value) TYPE i.
  PRIVATE 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.

DATA number TYPE i VALUE 5.

START-OF-SELECTION.

  DATA(cnt) = NEW counter( ).

  cnt->set( number ).

  DO 3 TIMES.
    cnt->increment( ).
  ENDDO.

  cnt->get( IMPORTING get_value = number ).

  cl_demo_output=>display( number ).

Description

The class counter contains three public methods, set, increment, and get, which work with the private integer field count. Two of the methods have input and output parameters that they use to define the data interface of the class. The field count, on the other hand, is not visible from the outside.