Entering content frameInterfaces - Introductory Example  Locate the document in its SAP Library structure

The following simple example shows how you can use an interface to implement two counters that are different, but can be addressed in the same way. See also the example in the Classes section.

Example

INTERFACE I_COUNTER.
  METHODS: SET_COUNTER IMPORTING VALUE(SET_VALUE) TYPE I,
           INCREMENT_COUNTER,
           GET_COUNTER EXPORTING VALUE(GET_VALUE) TYPE I.
ENDINTERFACE.

CLASS C_COUNTER1 DEFINITION.
  PUBLIC SECTION.
    INTERFACES I_COUNTER.
  PRIVATE SECTION.
    DATA COUNT TYPE I.
ENDCLASS.

CLASS C_COUNTER1 IMPLEMENTATION.
  METHOD I_COUNTER~SET_COUNTER.
    COUNT = SET_VALUE.
  ENDMETHOD.
  METHOD I_COUNTER~INCREMENT_COUNTER.
    ADD 1 TO COUNT.
  ENDMETHOD.
  METHOD I_COUNTER~GET_COUNTER.
    GET_VALUE = COUNT.
  ENDMETHOD.
ENDCLASS.

CLASS C_COUNTER2 DEFINITION.
  PUBLIC SECTION.
    INTERFACES I_COUNTER.
  PRIVATE SECTION.
    DATA COUNT TYPE I.
ENDCLASS.

CLASS C_COUNTER2 IMPLEMENTATION.
  METHOD I_COUNTER~SET_COUNTER.
    COUNT = ( SET_VALUE / 10) * 10.
  ENDMETHOD.
  METHOD I_COUNTER~INCREMENT_COUNTER.
    IF COUNT GE 100.
      MESSAGE I042(00).
      COUNT = 0.
    ELSE.
      ADD 10 TO COUNT.
    ENDIF.
  ENDMETHOD.
  METHOD I_COUNTER~GET_COUNTER.
    GET_VALUE = COUNT.
  ENDMETHOD.
ENDCLASS.

The interface I_COUNTER contains three methods SET_COUNTER, INCREMENT_COUNTER, and GET_COUNTER. The classes C_COUNTER1 and C_COUNTER2 implement the interface in the public section. Both classes must implement the three interface methods in their implementation part. C_COUNTER1 is a class for counters that can have any starting value and are then increased by one. C_COUNTER2 is a class for counters that can only be increased in steps of 10. Both classes have an identical outward face. It is fully defined by the interface in both cases.

The following sections explain how a user can use an interface reference to address the objects of both classes:

This graphic is explained in the accompanying text

 

 

 

Leaving content frame