Delegation is an Object Oriented Programming concept that involves using another, more specialised Class to do a big job. In other words, we can delegate a big task to various other classes to avoid large class definitions, and extend functionality. The two classes (and their subsequent Objects) are now associated, as we have defined a relationship between them that allows one to use the other in some way.
The association can be defined through Composition or Inheritance
Example
Imagine we have a Square
class, defined with a side length. Imagine we also have a Rect
(Rectangle) class, defined with width and height. We know that both rectangles and squares have the same area formula: . The area of a square is just the area of a rectangle where width = height. As such, we can delegate the area formula to the rectangle
OLD:
public class Square {
private double sideLength;
//Other code (like constructors) goes here.
public double getArea()
{
return sideLength * sideLength;
}
}
---
public class Rect {
private double height, width;
public Rect(double height, double width)
{
this.height = height;
this.width = width;
}
public double getArea()
{
return height * width;
}
}
NEW:
public class Square {
private double sideLength;
//Other code (like constructors) goes here.
//Delegation via composition
private Rect rect = new Rect(sideLength, sideLength);
public double getArea()
{
//Delegated area function to Rec
return rect.getArea();
}
}