Java interfaces and composition
Depend on a contract and inject a collaborating object.
On this page
Classes, constructors, and methods.
- Depend on a contract and inject a collaborating object.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
An interface declares operations that implementing classes provide. A Report receives a Formatter rather than constructing one hard-coded implementation internally.
Report has a formatter; it is not a formatter. This composition makes it possible to change formatting behavior while keeping report logic unchanged.
Code example
interface Formatter {
String format(String text);
}
class BracketFormatter implements Formatter {
public String format(String text) { return "[" + text + "]"; }
}
class Report {
private final Formatter formatter;
Report(Formatter formatter) { this.formatter = formatter; }
String render() { return formatter.format("Ready"); }
}
class Main {
public static void main(String[] args) {
Report report = new Report(new BracketFormatter());
System.out.println(report.render());
}
}[Ready]
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
interface Formatter { String format(String text);}class BracketFormatter implements Formatter { public String format(String text) { return "[" + text + "]"; }}class Report { private final Formatter formatter; Report(Formatter formatter) { this.formatter = formatter; } String render() { return formatter.format("Ready"); }}class Main { public static void main(String[] args) { Report report = new Report(new BracketFormatter()); System.out.println(report.render()); }}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Construct and inject a formatter. | report.formatter = BracketFormatter | — | |
| Delegate through the interface. | text = Ready | — | |
| The implementation wraps the text. | return = [Ready] | — | |
| Print the rendered result. | return = [Ready] | [Ready] |
Behind the scenes
How Java processes this code
The Java compiler produces bytecode. The JVM loads the class and invokes its main method.
Cost and common mistakes
O(n) time and space to construct formatted text of length n.
- A final reference cannot be reassigned, but does not automatically make the referenced object immutable.
- This example expects a non-null formatter; production constructors should enforce required dependencies.
Try it yourself
Implement a formatter that adds parentheses.
Reveal answer and reasoning
Return '(' + text + ')' as a string expression. Inject it to produce (Ready).