Java language
Java Constructor dependency injection
A caller supplies an object required by another object at construction. This design technique does not require a framework. Validate required references.
Formal Syntax & Structure
java syntaxjava
Delivery(Rate rate) { this.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)); }}