Skip to lesson

Delegation: let another object do the work

Delegation means an object receives a request and hands the real work to another object it holds. A laptop does not print; it asks its printer. A checkout does not move money; it asks a payment method. The object that does the work is the delegate.

Forwarding a call to a part

Delegation is a design in which an object receives a request and hands the actual work to another object it holds, called the delegate. The caller talks to one object; the work happens in the other.

The simplest delegation is a method whose body just calls the same job on a part: void print(String doc) { printer.print(doc); }. To the caller, the laptop prints.

Example 1 · A forwarding method

ForwardDemo.javaJava
class Printer {    void print(String doc) {        System.out.println("Printing " + doc + "...");    }}
class Laptop {    private String owner;    private Printer printer = new Printer();
    Laptop(String owner) { this.owner = owner; }
    void print(String doc) {        printer.print(doc);    }}
public class ForwardDemo {    public static void main(String[] args) {        Laptop l = new Laptop("Priya");        l.print("Resume.pdf");        l.print("Hall ticket.pdf");    }}
Output
Printing Resume.pdf...
Printing Hall ticket.pdf...

What this code does

  • Laptop.print does no printing itself; its only line passes the job to the printer. This is a forwarding method.
  • Callers talk to the laptop and never see the printer. The laptop chose to offer print, nothing more.

Such a method is called a forwarding method. Delegation is how HAS-A reuses code: extends gives a child every parent method automatically, while a whole chooses which jobs to pass on, as the Stack did with its private list in HAS-A vs IS-A (opens in a new tab).

Adding your own steps around the work

A delegating method can do more than forward. It can check the input, call the delegate, and then do something after, such as update a count or write a log line.

Example 2 · Delegating with checks and a log

LoggerDemo.javaJava
class Logger {    void log(String message) {        System.out.println("[LOG] " + message);    }}
class BankAccount {    private int balance;    private Logger logger = new Logger();
    void deposit(int amount) {        if (amount <= 0) {            logger.log("Rejected deposit of Rs. " + amount);            return;        }        balance = balance + amount;        logger.log("Deposited Rs. " + amount + ", balance Rs. " + balance);    }}
public class LoggerDemo {    public static void main(String[] args) {        BankAccount acc = new BankAccount();        acc.deposit(500);        acc.deposit(-20);        acc.deposit(250);    }}
Output
[LOG] Deposited Rs. 500, balance Rs. 500
[LOG] Rejected deposit of Rs. -20
[LOG] Deposited Rs. 250, balance Rs. 750

What this code does

  • The account does its own job first (check and change the balance), then delegates writing the message to the logger.
  • If the log format must change, only Logger changes. BankAccount stays the same.

The account keeps its money rules; the logger only knows how to write messages. Each class stays small with one job, so a change to the log format touches only Logger.

Delegate to an interface, swap at run time

Give the delegate field an interface type, private PaymentMethod method;, and any class that implements it can be plugged in. The checkout calls method.pay(amount) and does not care which one it got.

Example 3 · Delegating to an interface

PaymentDemo.javaJava
interface PaymentMethod {    void pay(int amount);}
class UpiPayment implements PaymentMethod {    public void pay(int amount) {        System.out.println("Paid Rs. " + amount + " by UPI");    }}
class CardPayment implements PaymentMethod {    public void pay(int amount) {        System.out.println("Paid Rs. " + amount + " by card");    }}
class Checkout {    private PaymentMethod method;
    Checkout(PaymentMethod method) { this.method = method; }
    void complete(int amount) {        System.out.println("Order total: Rs. " + amount);        method.pay(amount);    }}
public class PaymentDemo {    public static void main(String[] args) {        Checkout a = new Checkout(new UpiPayment());        Checkout b = new Checkout(new CardPayment());        a.complete(349);        b.complete(1299);    }}
Output
Order total: Rs. 349
Paid Rs. 349 by UPI
Order total: Rs. 1299
Paid Rs. 1299 by card

What this code does

  • The field has the interface type PaymentMethod, so any implementation can be handed in through the constructor.
  • Checkout has one complete method, yet the two objects pay differently. The delegate decides how.

Example 4 · Swapping the delegate at run time

SwapDemo.javaJava
interface PaymentMethod {    boolean pay(int amount);}
class UpiPayment implements PaymentMethod {    public boolean pay(int amount) {        if (amount > 1000) {            System.out.println("UPI limit crossed for Rs. " + amount);            return false;        }        System.out.println("Paid Rs. " + amount + " by UPI");        return true;    }}
class CardPayment implements PaymentMethod {    public boolean pay(int amount) {        System.out.println("Paid Rs. " + amount + " by card");        return true;    }}
class Checkout {    private PaymentMethod method;
    Checkout(PaymentMethod method) { this.method = method; }
    void setMethod(PaymentMethod method) { this.method = method; }
    boolean complete(int amount) { return method.pay(amount); }}
public class SwapDemo {    public static void main(String[] args) {        Checkout c = new Checkout(new UpiPayment());        c.complete(400);        if (!c.complete(2500)) {            c.setMethod(new CardPayment());            c.complete(2500);        }    }}
Output
Paid Rs. 400 by UPI
UPI limit crossed for Rs. 2500
Paid Rs. 2500 by card

What this code does

  • The same Checkout object pays first by UPI, then switches to card with setMethod when UPI refuses.
  • With inheritance (UpiCheckout extends Checkout) this is impossible: an object cannot change its class while running.

Example 5 · A lambda as the delegate

LambdaDelegateDemo.javaJava
interface PaymentMethod {    void pay(int amount);}
class Checkout {    private PaymentMethod method;
    Checkout(PaymentMethod method) {        if (method == null) {            throw new IllegalArgumentException("A payment method is required");        }        this.method = method;    }
    void complete(int amount) { method.pay(amount); }}
public class LambdaDelegateDemo {    public static void main(String[] args) {        Checkout cash = new Checkout(amount -> System.out.println("Collect Rs. " + amount + " in cash"));        cash.complete(560);        try {            new Checkout(null);        } catch (IllegalArgumentException e) {            System.out.println("Error: " + e.getMessage());        }    }}
Output
Collect Rs. 560 in cash
Error: A payment method is required

What this code does

  • PaymentMethod has one abstract method, so it is a functional interface and a lambda can be the delegate. No extra class needed.
  • The constructor refuses null, so a Checkout without a payment method can never be created.

Dynamic method dispatch (opens in a new tab) runs the right pay for the real object. With a setter the behaviour can change while the program runs, which inheritance cannot do: an object's class is fixed when it is created.

When the interface has one abstract method, a lambda can be the delegate, as in Functional interfaces and lambdas (opens in a new tab).

Traps: a missing delegate and forwarding everything

If the delegate field was never set, it is null, and the first forwarded call throws a NullPointerException. Take the delegate in the constructor and refuse null there, as Example 5 does.

Example 6 · A missing delegate

NoDelegateDemo.javaJava
interface PaymentMethod {    void pay(int amount);}
class Checkout {    private PaymentMethod method;
    void setMethod(PaymentMethod method) { this.method = method; }
    void complete(int amount) {        System.out.println("Order total: Rs. " + amount);        method.pay(amount);    }}
public class NoDelegateDemo {    public static void main(String[] args) {        Checkout c = new Checkout();        c.complete(199);    }}
Sample output
Order total: Rs. 199
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "PaymentMethod.pay(int)" because "this.method" is null
	at Checkout.complete(NoDelegateDemo.java:12)
	at NoDelegateDemo.main(NoDelegateDemo.java:19)

What this code does

  • Nobody called setMethod, so method is still null. The first line prints, then the forwarded call crashes.
  • Fix: make the delegate a constructor parameter, so a Checkout cannot exist without one, and reject null there.

The second trap is forwarding every method of the part without thinking. Then you have rebuilt inheritance by hand, including the methods that should stay hidden. Forward only what the whole's callers really need.

Fix the error

Fix the missing delegate

Read the error, then pick the line that fixes it.

Round 1 of 2

The laptop should forward print() to its printer.

class Printer {
void print(String doc) { System.out.println("Printing " + doc + "..."); }
}
class Laptop {
private Printer printer;
void print(String doc) { printer.print(doc); }
}
public class ForwardDemo {
public static void main(String[] args) {
new Laptop().print("Resume.pdf");
}
}

Error

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Printer.print(String)" because "this.printer" is null
	at Laptop.print(ForwardDemo.java:6)

Next step

Check your understanding

11 quick questions