Mentor SAP
2017-07-24 Submitted by:- Admin

An interface can be instantiated if the object is referenced to that interface. Here the class instance variable will have to be moved to the interface instance variable.

 

Following is a program where we have declared an interface containing constant, data and a method. Now the class definition contains only the interface in the public section. After that the method is implemented accordingly. In the start of selection, we have created objects of the class. Here we have moved the class object variable to the interface variable and then we have called the method directly from the interface object variable.

REPORT zinterface_instantiate.

*----------------------------------------------------------------------*
*       INTERFACE it
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
INTERFACE it.
  CONSTANTS c_var TYPE char40 VALUE 'SAP ABAP Object Oriented'.
  DATA var TYPE char50.
  METHODS mit.
ENDINTERFACE.                    "it

*----------------------------------------------------------------------*
*       CLASS cls DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cls DEFINITION.
  PUBLIC SECTION.
    INTERFACES it.
ENDCLASS.                    "cls DEFINITION

*----------------------------------------------------------------------*
*       CLASS cls IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cls IMPLEMENTATION.
  METHOD it~mit.
    it~var = 'Interface Attribute'.
    WRITE: / 'Interface Method',
           / it~var,
           / it~c_var.
  ENDMETHOD.                    "it~mit
ENDCLASS.                    "cls IMPLEMENTATION

START-OF-SELECTION.

* Data Declaration
  DATA: obj_it TYPE REF TO it,
        obj    TYPE REF TO cls.

* Object Creation
  CREATE OBJECT obj.

* Narrow Casting
  obj_it = obj.

* Method call
  CALL METHOD obj_it->mit.

 

Output