Documente Academic
Documente Profesional
Documente Cultură
A Class can grant friendship to another class. By granting friendship, it allows another
class to:-
Ex:-
1. Class C2 is created using CREATE PRIVATE option. That means only the class itself
and its friends can instantiate this class.
2. 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.
Program:-
PROTECTED SECTION.
METHODS : M2.
ENDCLASS.
CLASS C2 IMPLEMENTATION.
METHOD M2.
ENDMETHOD.
ENDCLASS.
CLASS C1 DEFINITION.
PUBLIC SECTION.
METHODS: M1.
ENDCLASS.
CLASS C1 IMPLEMENTATION.
METHOD M1.
WRITE:/5 OREF2->NUM.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
Output:-
I am method M2 in C2.
Subclasses of the friend class are also friends of the class granting friendship (to their
super classes).
Ex:-
1. Class C2 has granted friendship to class C1. Hence, C1 is friend of class C2.
Program:-
PROTECTED SECTION.
ENDCLASS.
CLASS C2 IMPLEMENTATION.
ENDCLASS.
CLASS C1 DEFINITION.
PUBLIC SECTION.
METHODS: M1.
ENDCLASS.
CLASS C1 IMPLEMENTATION.
METHOD M1.
WRITE:/5 OREF2->NUM.
ENDMETHOD.
ENDCLASS.
PUBLIC SECTION.
METHODS: M11.
ENDCLASS.
METHOD M11.
WRITE:/5 OREF2->NUM.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
Output:-
Ex:-
1. Class C2 grants friendship to class C1. Hence, class C1 can access protected
attribute (num2) of C2.
2. But, Class C2 cannot access protected attribute (num1) of class C1. This is because
friendship is one-sided.
3. To allow C2 access protected attribute of C1, class C1 must also declare C2 as its
friend.
Program:-
Wrong way:-
CLASS C1 DEFINITION.
PUBLIC SECTION.
METHODS:METHPUB.
PRIVATE SECTION.
DATA: NUM1 TYPE I VALUE 10.
METHODS: M1.
ENDCLASS.
CLASS C2 IMPLEMENTATION.
METHOD M2.
DATA: OREF1 TYPE REF TO C1.
CREATE OBJECT OREF1.
WRITE:/5 OREF1->NUM1.
ENDMETHOD.
ENDCLASS.
CLASS C1 IMPLEMENTATION.
METHOD M1.
DATA: OREF2 TYPE REF TO C2.
CREATE OBJECT OREF2.
WRITE:/5 OREF2->NUM2.
ENDMETHOD.
METHOD METHPUB.
CALL METHOD M1.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA: OREF TYPE REF TO C1.
CREATE OBJECT OREF.
CALL METHOD OREF->METHPUB.
Correct way:-
CLASS C2 IMPLEMENTATION.
METHOD M2.
DATA: OREF1 TYPE REF TO C1.
CREATE OBJECT OREF1.
WRITE:/5 OREF1->NUM1.
ENDMETHOD.
ENDCLASS.
CLASS C1 IMPLEMENTATION.
METHOD M1.
DATA: OREF2 TYPE REF TO C2.
CREATE OBJECT OREF2.
WRITE:/5 OREF2->NUM2.
ENDMETHOD.
METHOD METHPUB.
CALL METHOD M1.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
Output:-
15
A class may not be instantiated by anyone (private constructor) but a corresponding factory is
reponsible to create the class in a consistent fashion.
Therefore you may declare the factory-class being a friend of the to-be-instantiated class.