Java language
Java Object composition and delegation
A class can store a collaborator and call its methods. A reference field does not enforce exclusive ownership, immutability or resource cleanup.
Formal Syntax & Structure
java syntaxjava
private final Rate rate;Working Example
Example Snippetjava
class Rate { private final int centsPerItem; Rate(int centsPerItem) { if (centsPerItem < 0 || centsPerItem > 1000) throw new IllegalArgumentException("rate outside range"); this.centsPerItem = centsPerItem; } public int cost(int items) { if (items < 0 || items > 1000) throw new IllegalArgumentException("items outside range"); return centsPerItem * items; }}class Delivery { private final Rate rate; Delivery(Rate rate) { if (rate == null) throw new IllegalArgumentException("missing rate"); this.rate = rate; } public int quote(int items) { return rate.cost(items); }}public class Main { public static void main(String[] args) { Delivery local = new Delivery(new Rate(40)); Delivery distant = new Delivery(new Rate(65)); System.out.println(local.quote(3)); System.out.println(distant.quote(3)); }}