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:
public class Employee {
public void performSomeWork() {
System.out.println("I am performing 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:
public class Business {
// assuming this business only has one employee
private Employee employee;
}
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:
public class Business {
// assuming this business only has one employee
private Employee employee;
// Assign empployee in constructor
public Business(Employee employee) {
this.employee = employee;
}
public void performSomeWork() {
// delegate to the employee
employee.performSomeWork();
}
}
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:
public class Employee {
public int performSomeWork(int a, int b) {
// return the sum of a and b
return a + b;
}
}
To make this work, we need to amend the performSomeWork() method in Business:
public class Business {
// assuming this business only has one employee
private Employee employee;
// Assign empployee in constructor
public Business(Employee employee) {
this.employee = employee;
}
public int performSomeWork(int a, int b) {
// delegate to the employee
return employee.performSomeWork(a, b);
}
}
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:
public int performSomeWork(Employee employee, int a, int b) {
// delegate to the employee
return employee.performSomeWork(a, b);
}
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: