Java ProgramsOOPDependency

Dependency in Java

beginner·  OOP  ·  Relationships

Problem

Dependency is the weakest relationship between two classes — one uses the other only momentarily, typically as a method parameter, without keeping any lasting reference to it.

Model a Printer whose print() method uses a Document only for that one call, without ever storing a reference to it as a field.

Input
new Printer().print(new Document("Invoice #245"))
Output
Printing: Invoice #245

Java Program

Java
class Document { String content; Document(String content) { this.content = content; } } class Printer { // Document is used only for this one call — no field stores a reference to it void print(Document doc) { System.out.println("Printing: " + doc.content); } } public class DependencyDemo { public static void main(String[] args) { Printer printer = new Printer(); printer.print(new Document("Invoice #245")); } }

Output

Printing: Invoice #245

Core Logic

Passing the Document in only as a method parameter, with Printer never assigning it to a field, means the relationship lasts exactly as long as that one method call and no longer.

How It Works
  1. 1Printer has no field of type Document anywhere in its declaration.
  2. 2print(Document doc) receives a Document only as a parameter, uses it to print its content, and then the parameter goes out of scope once the method returns.
  3. 3new Document("Invoice #245") is created right at the call site and never referenced again afterward.
  4. 4Nothing about Printer's own state changes or remembers anything about which Document it last printed.
Calling printer.print(new Document("Invoice #245")) uses that one Document object for the single call, printing "Printing: Invoice #245", and the object is gone as soon as the call returns.
💡

Key Point: Association implies an ongoing reference, usually stored in a field, that outlives any single method call; dependency is just a momentary use during one call, with nothing kept around afterward.

Key Concepts

dependencymethod parameterno stored reference

Related Programs