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

DATA number TYPE i VALUE 5.
DATA cnt TYPE REF TO counter.

START-OF-SELECTION.

  CREATE OBJECT cnt.

  cnt->set( number ).

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

  cnt->get( IMPORTING get_value = number ).

  cl_demo_output=>display( number ).

Description

The counter class 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 with which they define the data interface of the class. The field count is not visible externally.