Dependency
A "uses-a" relationship where one class depends on another temporarily.
What is Dependency?
Dependency is the weakest relationship between classes. Class A depends on Class B when A uses B temporarily - typically as a method parameter, local variable, or return type.
Key Point: No ownership. Class A just uses Class B for a specific operation.
Real-World Analogy
Person and Taxi
A person uses a taxi to get somewhere. They don't own the taxi - just use it temporarily.
Chef and Recipe
A chef uses a recipe to cook. The recipe exists independently and can be used by many chefs.
UML Representation
┌─────────────┐ ┌─────────────┐
│ Client │- - - - ▷│ Service │
└─────────────┘ uses └─────────────┘
- - - ▷ = Dashed arrow (Dependency)
Weakest relationshipTypes of Dependency
Method Parameter
void process(Validator validator)Class receives dependency as parameter
Local Variable
Formatter formatter = new Formatter()Class creates dependency inside method
Return Type
Report generateReport()Method returns instance of another class
Static Method Call
Logger.log(message)Class calls static methods of another
Code Example
// Dependency: OrderService uses EmailService
// No ownership - just uses it for sending
class EmailService {
public void send(String to, String message) {
System.out.println("Sending email to " + to);
}
}
class OrderService {
// Dependency via method parameter
public void placeOrder(Order order, EmailService emailService) {
// Process order...
order.setStatus("PLACED");
// Use EmailService temporarily
emailService.send(
order.getCustomerEmail(),
"Your order has been placed!"
);
}
}
// Usage
OrderService orderService = new OrderService();
EmailService emailService = new EmailService();
orderService.placeOrder(order, emailService);
// OrderService doesn't own EmailServiceDependency vs Other Relationships
| Relationship | Strength | Ownership | Duration |
|---|---|---|---|
| Dependency | Weakest | None | Temporary (method scope) |
| Association | Weak | None | Longer (field reference) |
| Aggregation | Medium | Weak ownership | Object lifetime |
| Composition | Strongest | Full ownership | Same as parent |
Interview Tips
- 1.Dependency = "uses" temporarily, not "has" permanently
- 2.Minimize dependencies to reduce coupling
- 3.Use Dependency Injection to manage dependencies cleanly
- 4.Depend on abstractions (interfaces), not concretions