Composition means building one object using other objects with focused responsibilities. A report needs a formatter; a formatter does not need to become a report's parent class. Passing a dependency into a constructor makes that relationship explicit and lets tests substitute a simple implementation.
Work through the example
Report owns a Formatter reference supplied by its caller. Its line method decides the report prefix and delegates the title formatting. The constructor rejects null immediately, so later report calls can rely on a valid collaborator.
This is often called dependency injection. Here it is just a constructor parameter, with no framework or container. Do not create an interface for every class automatically: use one where callers need a useful boundary or interchangeable behavior. Preserve the difference between “has a formatter” and “is a formatter.”
Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.
public class Main {
public static void main(String[] args) {
Report report = new Report(new Brackets());
System.out.println(report.line("Read"));
}
}
interface Formatter {
String format(String title);
}
final class Brackets implements Formatter {
public String format(String title) {
return "[" + title + "]";
}
}
final class Report {
private final Formatter formatter;
Report(Formatter formatter) {
if (formatter == null) {
throw new IllegalArgumentException("formatter required");
}
this.formatter = formatter;
}
String line(String title) {
return "Task: " + formatter.format(title);
}
}Check your prediction
Task: [Read]Compare the behavior
A test double is an implementation chosen for a test. A FixedSource supplies known data instead of reading unpredictable external input. The consumer still follows the same MinutesSource contract. Returning a known value makes the expected result deterministic: it does not depend on the clock, a network request or a person's response.
public class Main {
public static void main(String[] args) {
Summary summary = new Summary(new FixedSource());
System.out.println(summary.minutesRemaining(60));
}
}
interface MinutesSource {
int completed();
}
final class FixedSource implements MinutesSource {
public int completed() {
return 25;
}
}
final class Summary {
private final MinutesSource source;
Summary(MinutesSource source) {
if (source == null) {
throw new IllegalArgumentException("source required");
}
this.source = source;
}
int minutesRemaining(int target) {
return target - source.completed();
}
}Check your prediction
35Follow the dependency from construction to use
A constructor parameter makes the collaborator choice visible. Main chooses the formatter, Report stores the Formatter reference, and line delegates only the formatting step. Report still owns its prefix. Changing the collaborator changes one policy without requiring callers to rewrite the report layout.
A test double can provide a fixed answer that is easy to check independently. It need not imitate a whole real service or make a network request. The important property is preserving the same contract from the consumer's point of view. Test the consumer with two implementations whose answers differ so a consumer that ignores its dependency cannot pass accidentally.
A final collaborator reference prevents replacement of that reference, but does not imply the collaborator itself is immutable. Be precise about what is shared. For today's fixed formatter and data-source examples, construction and deterministic answers make the relationship straightforward to inspect.
Debug a plausible mistake
The consumer can accept a dependency yet ignore it. Merely declaring an interface field does not prove the runtime behavior is interchangeable. Test two visibly different implementations through the same consumer.
Repair ignored dependency injection
Report must use the supplied Formatter. With Brackets, print [Read]. Then supply Plain and expect Read without editing Report. Keep title formatting inside the collaborator. Predict what the current program actually prints before changing it. Make the smallest repair, then pass new Plain() to Report and expect Read. The supplied version compiles; its behavior is the problem.
public class Main {
public static void main(String[] args) {
Report report = new Report(new Brackets());
System.out.println(report.line("Read"));
}
}
interface Formatter {
String format(String title);
}
final class Plain implements Formatter {
public String format(String title) {
return title;
}
}
final class Brackets implements Formatter {
public String format(String title) {
return "[" + title + "]";
}
}
final class Report {
private final Formatter formatter;
Report(Formatter formatter) {
this.formatter = formatter;
}
String line(String title) {
return new Plain().format(title);
}
}Hint 1: the idea
The caller already chose an implementation; creating another one discards that choice.
Hint 2: a first step
Delegate to the stored interface reference inside line.
Show one solution
public class Main {
public static void main(String[] args) {
Report report = new Report(new Brackets());
System.out.println(report.line("Read"));
}
}
interface Formatter {
String format(String title);
}
final class Plain implements Formatter {
public String format(String title) {
return title;
}
}
final class Brackets implements Formatter {
public String format(String title) {
return "[" + title + "]";
}
}
final class Report {
private final Formatter formatter;
Report(Formatter formatter) {
this.formatter = formatter;
}
String line(String title) {
return formatter.format(title);
}
}Expected output after repair:
[Read]The bug was new Plain().format(title) inside line(): Report stored the
caller's formatter and then ignored it, so the program printed Read. Calling
formatter.format(title) uses whichever implementation was passed in. Note
that the Plain case alone could never have exposed this bug, since the broken
version printed Read too; only the Brackets case shows the injected formatter
is really used.
Practice independently
Composition & Dependencies: practice
Define a Greeting interface with String text(). A Welcome receives a Greeting and returns "Welcome: " plus that text from message(). Reject null in Welcome's constructor. Supply a FixedGreeting returning "Java", and print Welcome: Java.
Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.
public class Main {
public static void main(String[] args) {
System.out.println("Build Welcome from a Greeting");
}
}Hint 1: the idea
The composing object stores the contract type. The caller selects an implementation.
Hint 2: a first step
Give Welcome a final Greeting field and assign it in the constructor after validation.
Show one solution
One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?
public class Main {
public static void main(String[] args) {
Welcome welcome = new Welcome(new FixedGreeting());
System.out.println(welcome.message());
}
}
interface Greeting {
String text();
}
final class FixedGreeting implements Greeting {
public String text() {
return "Java";
}
}
final class Welcome {
private final Greeting greeting;
Welcome(Greeting greeting) {
if (greeting == null) {
throw new IllegalArgumentException("greeting required");
}
this.greeting = greeting;
}
String message() {
return "Welcome: " + greeting.text();
}
}Expected output:
Welcome: JavaChange it and test again
Add a second Greeting returning "Tests" and check Welcome without changing its class. Then reject a null collaborator in a test. Which changes belong to the greeting policy and which belong to Welcome's message layout?
Explain before moving on
Explain why this design does not require inheritance. Which dependency would be difficult to test if the constructor created its own live network client? No network is needed for this course.
Completion is saved in this browser only. It does not measure mastery.