SAP Tech Pro

SAP Technical Blog
Topprice Price Comparison

Object Oriented Programming in ABAP - Friendship between Classes

Object Oriented Programming in ABAP - Friendship between Classes

A class can grant friendship to another class. By granting friendship, it allows another class to:-

  • Use its private components.
  • Instantiate it, irrespective of the CREATE PRIVATE addition.

Program -

  • Class C2 is created using CREATE PRIVATE option. That means, only the class itself and its friends can instantiate this class.
  • Class C2 has a private method M2 and a private attribute , NUM. This means that these components can be accessed by class C2 itself and its friends.
  • Now, C2 has granted friendship to class C1.
  • So, methods of class C1 can access private components of C2 as well as can instantiate class C2.

This establishes the theme.



REPORT zstp_oo_abap.

CLASS c1 DEFINITION DEFERRED.

CLASS c2 DEFINITION CREATE PRIVATE FRIENDS c1  .
  PROTECTED SECTION.
    DATA : num TYPE i VALUE 5.
    METHODS : m2.
ENDCLASS.

CLASS c2 IMPLEMENTATION.
  METHOD  m2.
    WRITE:/5 'I am method m2 in C2'.
  ENDMETHOD.
ENDCLASS .

CLASS c1 DEFINITION.
  PUBLIC SECTION .
    METHODS : m1.
ENDCLASS.

CLASS c1 IMPLEMENTATION.
  METHOD m1.
    DATA : oref2 TYPE REF TO c2.
    CREATE OBJECT oref2.
    WRITE:/5 oref2->num.
    CALL METHOD oref2->m2.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  DATA : oref1 TYPE REF TO c1.
  CREATE OBJECT oref1.
  CALL METHOD oref1->m1.

Output -

Object Oriented Programming in ABAP - Friendship between Classes

Add comment

Before Buying, Compare Prices at Topprice.in

Topprice.in