SAP Tech Pro

SAP Technical Blog
Topprice Price Comparison

Object Oriented Programming in ABAP - Polymorphism via Interfaces

Object Oriented Programming in ABAP - Polymorphism via Interfaces

This program will demonstrate how a method of an interface can be interpreted differently in different classes. At runtime, one can use different class reference variables to call same method of the interface to have different things done.
Use of interface reference variable in this context further simplifies the work.

 

  • Both the classes C1 and C2 , totally different from each other, contains interface I1.
  • Interface I1 contains method M1 , which is implemented differently in C1 and C2.
  • In the START-OF-SELECTION block, objects are created from class C1 and C2. An Interface reference variable IREF is also defined.
  • By assigning the class reference variables( of C1 and C2 , one at a time) to interface reference variable IREF and then calling method M1 (using IREF) clearly demonstrates how polymorphism can be achieved using the concept of interface.


REPORT zstp_oo_abap.

INTERFACE i1.
  METHODS : m1 .
ENDINTERFACE.

CLASS c1 DEFINITION.
  PUBLIC SECTION.
    INTERFACES : i1.
ENDCLASS.

CLASS c1 IMPLEMENTATION.
  METHOD i1~m1.
    WRITE:/5 'I am method m1 in c1'.
  ENDMETHOD.
ENDCLASS.

CLASS c2 DEFINITION.
  PUBLIC SECTION.
    INTERFACES : i1.
ENDCLASS.

CLASS c2 IMPLEMENTATION.
  METHOD i1~m1.
    WRITE:/5 'I am method m1 in c2'.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  DATA : oref1 TYPE REF TO c1,
         oref2 TYPE REF TO c2,
         iref  TYPE REF TO i1.
  CREATE OBJECT : oref1 ,
                  oref2 .
  iref = oref1.
  CALL METHOD iref->m1.
  iref = oref2.
  CALL METHOD iref->m1.

Output -

Polymorphism via Interfaces

Add comment

Before Buying, Compare Prices at Topprice.in

Topprice.in