SAP Tech Pro

SAP Technical Blog
Topprice Price Comparison

Object Oriented Programming in ABAP - Subclasses of friends can also become friends

Object Oriented Programming in ABAP - Subclasses of friends can also become friends

Subclasses of the friend class are also friends of the class granting friendship( to their super classes).

  • Class C2 has granted friendship to class C1.Hence, C1 is friend of class C2.
  • Class C11 is a subclass of class C1.
  • So, class C11 is also a friend of class C2.Class C11 can thus access the protected components of class C2.

This establishes the theme.



REPORT zstp_oo_abap.

CLASS c1 DEFINITION DEFERRED.

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

CLASS c2 IMPLEMENTATION.
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.
  ENDMETHOD.
ENDCLASS.

CLASS c11 DEFINITION INHERITING FROM c1.
  PUBLIC SECTION.
    METHODS : m11.
ENDCLASS.

CLASS c11 IMPLEMENTATION.
  METHOD m11.
    DATA : oref2 TYPE REF TO c2.
    CREATE OBJECT oref2.
    WRITE:/5 oref2->num.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  DATA : oref11 TYPE REF TO c11.
  CREATE OBJECT oref11.
  CALL METHOD oref11->m11.

Output -

Subclasses of friends can also become friends

 

Friendship is one sided

In principle, granting of friendship is one-sided: A class granting a friendship is not automatically a friend of its friends. If the class granting the friendship wants to access the private components of a friend, then the latter has to explicitly grant friendship to the former.

  • Class C2 grants friendship to class C1. Hence, class C1 can access protected attribute(num2) of C2 .
  • But, class C2 cannot access protected attribute(num1) of class C1. This is because friendship is one-sided.
  • To allow C2 access protected attribute of C1, class C1 must also declare C2 as its friend.


REPORT zstp_oo_abap.

CLASS c1 DEFINITION DEFERRED.

CLASS c2 DEFINITION FRIENDS c1  .
  PROTECTED SECTION.
    DATA : num2 TYPE i VALUE 15.
    METHODS : m2.
ENDCLASS.

CLASS c1 DEFINITION FRIENDS c2.
  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. 

Output -

image

Add comment

Before Buying, Compare Prices at Topprice.in

Topprice.in