Forwarding (object-oriented programming)

The difference between forwarding and delegation is the binding of the self parameter in the wrappee when called through the wrapper.

While delegation is analogous to inheritance, allowing behavioral reuse (and concretely code reuse) without changing evaluation context, forwarding is analogous to composition, as execution depends only on the receiving (member) object, not the (original) sending object.

In both cases, reuse is dynamic, meaning determined at run time (based on the object to which use is delegated or forwarded), rather than static, meaning determined at compile/link time (based on the class which is inherited from).

Like inheritance, delegation allows the sending object to modify the original behavior, but is susceptible to problems analogous to the fragile base class; while forwarding provides stronger encapsulation and avoids these problems; see composition over inheritance.

[1] A simple example of explicit forwarding in Java: an instance of B forwards calls to the foo method of its a field: Note that when executing a.foo(), the this object is a (a subtype of A), not the original object (an instance of B).

Here is a simple example: The more complex case is a Decorator Pattern that by using interfaces, forwarding can be made more flexible and typesafe.

UML class diagram that illustrates forwarding.
UML class diagram that illustrates forwarding.