How to Use the Delegation Pattern in Java - dummies

How to Use the Delegation Pattern in Java

By Doug Lowe

Inheritance is one of the great features of object-oriented programming languages such as Java, but it isn’t the answer to every programming problem. Also, quite frankly, many Java programmers use it too much. In many cases, simply including an instance of one class in another class is easier than using inheritance. This technique is sometimes called the Delegation pattern.

Suppose that you need to create a class named EmployeeCollection that represents a group of employees. One way to create this class would be to extend one of the collection classes supplied by the Java API, such as the ArrayList class. Then your EmployeeCollection class would be a specialized version of the ArrayList class and would have all the methods that are available to the ArrayList class.

A simpler alternative, however, would be to declare a class field of type ArrayList within your EmployeeCollection class. Then you could provide methods that use this ArrayList object to add or retrieve employees from the collection.

Why is this technique called the delegation? Rather than write code that implements the functions of the collection, you delegate that task to an ArrayList object, because ArrayList objects already know how to perform these functions.