A friend class can access the protected and private components of another class. This is useful when you want to allow controlled access to internal details of a class without making them public.
CLASS main_class DEFINITION.
PUBLIC SECTION.
METHODS: display.
PRIVATE SECTION.
DATA: secret TYPE string VALUE ‘Top Secret’.
FRIENDS friend_class. ” grant access
ENDCLASS.
CLASS main_class IMPLEMENTATION.
METHOD display.
WRITE: / ‘Main class display:’, secret.
ENDMETHOD.
ENDCLASS.
CLASS friend_class DEFINITION.
PUBLIC SECTION.
METHODS: reveal IMPORTING obj TYPE REF TO main_class.
ENDCLASS.
CLASS friend_class IMPLEMENTATION.
METHOD reveal.
” Directly access the private attribute of main_class
WRITE: / ‘Friend class can access:’, obj->secret.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA(main) = NEW main_class( ).
DATA(frd) = NEW friend_class( ).
main->display( ).
frd->reveal( main ).
Output:
Main class display: Top Secret
Friend class can access: Top Secret