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.
- 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.
CLASS c1 DEFINITION DEFERRED.
CLASS c2 DEFINITION CREATE PRIVATE FRIENDS c1 .
DATA : num TYPE i VALUE 5.
METHODS : m2.
CLASS c2 IMPLEMENTATION.
WRITE:/5 'I am method m2 in C2'.
CLASS c1 DEFINITION.
PUBLIC SECTION .
METHODS : m1.
CLASS c1 IMPLEMENTATION.
DATA : oref2 TYPE REF TO c2.
CREATE OBJECT oref2.
CALL METHOD oref2->m2.
DATA : oref1 TYPE REF TO c1.
CREATE OBJECT oref1.
CALL METHOD oref1->m1.