By Tony Bevis on Monday, 11 December 2023
Category: Java

Method delegation in Java

Method delegation in Java

In this article I will show how you can delegate a method call from one Java object to another.

Let's start with a simple Employee class that contains a method to perform some work:

Now suppose we have a Business class (that represents a business of some type) that includes an Employee object as an instance variable:

The business can be asked by customers to perform some work, so the Business class will delegate that work to its employee.

To do this we define a delegating method in Business:

The method name performSomeWork() in Business does not need to be the same as that in Employee.

​To be slightly more sophisticated, the performSomeWork() method in Employee might require some value as a parameter and also return something.

Let's assume this is a simple calculation to add two values and return the result. Modify the performSomeWork() method in Employee:

To make this work, we need to amend the performSomeWork() method in Business:

A variation of the above could be that the business is told which Employee object to use, rather than its default one:

Add the following method to Business:

Above, the parameter name employee hides the instance variable of the same name, so that for the purposes of this method it uses the parameter variable instead of the instance variable.

Assuming you added the above method rather than replace the previous one, then this is known as method overloading, since you have two methods with the same name but different parameter lists (otherwise known as signatures).

You can learn more about overloading as part of my Java course:

Software Educator - Articles - Java programming course: 3.2 Method overloading

Related Posts

Leave Comments