Friends - Friendship Between Classes

In classes, there is normally a strict division between outside (PUBLIC) and inside (PROTECTED or PRIVATE). A user can only access the public components of a class. This permits changes to the implementation inside a class, without invalidating its users.

In rare cases, classes have to work together so closely that they need access to one anothers' protected or private components. In order to prevent these components being available to all users, there is the concept of friendship between classes.

Friends

A class can grant other classes and interfaces (and hence all classes that implement this interface) its friendship. This is the purpose served by the FRIENDS additions to the CLASS ... DEFINITION statement which lists all the classes and interfaces that are granted friendship. These friends gain access to the protected and private components of the class granting the friendship and can always create instances of this class, independently from the CLASS statement's CREATE addition.

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.

Inheritance, Interfaces, and Friendship

Subclasses of friends and interfaces that receive a friend as a component interface also become friends. Therefore extreme caution is advised when offering friendship. The higher up the inheritance hierarchy a friend is, the more subclasses gain access to all the components of the class offering the friendship. A class that offers its friendship to the root class OBJECT gains all the classes in the ABAP Objects world as its friend and therefore has no privacy whatsoever. On the other hand, it is reasonably safe for a class to offer friendship to a final class, because only then can it specify just this final class as a friend.

As opposed to the attribute of being the friend, the granting of friendship is not passed on. A friend of a superclass is therefore not automatically a friend of its subclasses.

The FRIENDS Additions

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