Understanding Relationships Between Objects
In object-oriented programming (OOP), relationships between objects are fundamental to designing flexible and maintainable systems.
These relationships define how objects interact, collaborate, and depend on each other to solve complex problems.
Key Relationships in OOP
- Dependency ("uses")
- Aggregation ("has-a")
- Inheritance ("is-a")
Imagine a traffic simulation model:
- Vehicle: Have subclasses CityCar and LargeTruck (inheritance).
- TrafficLight: Uses a Timer to control signals (dependency).
- Road: Has multiple Vehicle objects (aggregation).
Let's explore each of these relationships in detail.
Dependency ("Uses-a") Relationship
- A dependency relationship occurs when one object relies on another to function.
- This is often described as a "uses" relationship.
Dependency can be:
- Temporary: The relationship exists only when a specific action is performed.
- Unidirectional: One object depends on another, but not necessarily vice versa.
class Printer {
public void print(String message) {
System.out.println(message);
}
}
class Report {
public void generate() {
Printer printer = new Printer(); // used temporarily
printer.print("Report generated");
}
}Here, Report depends on Printer to print
NoteIn UML diagrams, dependency is represented by a dashed arrow pointing from the dependent class to the class it depends on.

Dependency is useful for allowing objects to interact without being tightly coupled.
TipWhen designing systems, aim to minimise dependencies.
Why Reduce Dependencies?
- Maintenance overheads: High dependencies mean changes in one object can ripple through the system.
- Code reusability: Strong dependencies make it hard to reuse code in different contexts.
- Flexibility: Reducing dependencies allows for easier updates and modifications.
- Aim to design objects that are loosely coupled.
- This means they interact with each other through well-defined interfaces, minimising direct dependencies.
Imagine an address book that needs to read contact data from a local file, database, or network.
- Initial design: The AddressBook class depends on three separate objects: LocalFileReader, DatabaseReader, and NetworkReader.
- New design: Introduce an InputStreamReader object that handles all data sources.
- Result: The AddressBook now depends only on InputStreamReader, reducing maintenance overhead.