ABAP - Keyword Documentation →  ABAP - Reference →  Declarations →  Declaration Statements →  Classes and Interfaces →  ABAP Objects - Overview → 

Friends - Friendship Between Classes

There is normally a strict division between external (PUBLIC) and internal (PROTECTED and PRIVATE) classes. A consumer can only access the public components of a class. This allows the internal implementation of a class to be changed without invalidating its consumers.

In rare cases, however, classes have to work so closely together that they require access to their mutually invisible components. The concept of friendship between classes was developed so that these components do not need to be made available to all consumers at the same time.

Friends

A class can grant friendship to other classes and interfaces (and thus to all classes that implement this interface). This relationship is created using the FRIENDS additions of the statement CLASS ... DEFINITION by specifying all classes and interfaces to which friendship is to be granted. These friends are granted access to all components of the class offering the friendship, regardless of their visibility section or the addition READ-ONLY and can always create instances of this class regardless of the addition CREATE of the statement CLASS.

Note

We advise caution when granting a global interface friendship. Each class that implements the interface becomes a friend of the class granting the friendship. If a global interface is used, the extent of this friendship should be limited using the package concept, for example.

Friendship is unilateral

Friendship is a unilateral principle. A class that grants friendship is not automatically a friend of its friends. If the class that grants friendship wants to access the private or protected components of its friend, the latter must grant friendship explicitly.

Inheritance, Interfaces, and Friendship

Subclasses of friends and interfaces that are assigned a friend as a component interface also become friends. For this reason, extreme care should be taken when defining a friendship. The higher a friend is in the inheritance tree, the greater the number of subclasses that can access all of the components of the class granting friendship. A class that grants friendship to the root class object gains all of the ABAP Objects classes as friends and therefore has no privacy whatsoever. Conversely, it is relatively safe to grant friendship to a final class since this class alone is specified as a friend.

Friendship granted is not inherited, in contrast to the friend attribute. A friend of a superclass is, therefore, not automatically a friend of its subclasses.

The FRIENDS Additions

The statement CLASS ... DEFINITION has three FRIENDS additions:

Executable Example

Friendship