banner ads

Interface is declared in Public Section of Class

Interface can only be declared in the public section of any class. Any other section will cause syntax error in the system.

Here is a program where we have declared an Interface it. We have defined attribute and method in this interface. Next we have defined class where we have declared the interface in the protected section. After implementing the method we compile the program and a syntax error has come as follows. 





Below is another version of the program where we have commented the protected section. And this time the program compiles successfully as produce the proper output.

*&---------------------------------------------------------------------*
*& Report ZTEST_INTERFACE
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT ztest_interface.

INTERFACE it.
  DATA lv_num1 TYPE i,
         lv_num2 TYPE i,
         lv_res  TYPE i.

  METHODS meth_calculation.
ENDINTERFACE.

*&---------------------Class 1------------------------------------------------*
CLASS cls_1 DEFINITION.
  public SECTION.
  INTERFACEs it DATA VALUES lv_num1 '10' lv_num2 '5'  .
ENDCLASS.


CLASS cls_1 IMPLEMENTATION.
 METHOD it~meth_calculation.
   it~lv_res it~lv_num1 + it~lv_num2"Addition
    write it~lv_res.
 ENDMETHOD.
 endclass.

*&---------------------Class 2------------------------------------------------*
CLASS cls_2 DEFINITION.
  public SECTION.
  INTERFACEs it DATA VALUES lv_num1 '20' lv_num2 '8'  .
ENDCLASS.


CLASS cls_2 IMPLEMENTATION.
 METHOD it~meth_calculation.
   it~lv_res it~lv_num1 it~lv_num2"Subtraction
    write it~lv_res.
 ENDMETHOD.
endclass.

*&---------------------Calling Interface method---------------------------------*
start-OF-SELECTION.

data lo_Ref_1 TYPE REF TO cls_1,
       lo_ref_2 TYPE REF TO cls_2.

create OBJECT lo_Ref_1.
CREATE OBJECT lo_ref_2.


WRITE 'Addition of two number'.

call METHOD lo_Ref_1->it~meth_calculation.

SKIP.
SKIP.

WRITE 'Subtraction of two number'.

call METHOD lo_ref_2->it~meth_calculation.


The output is following:



No comments