// Dependent class
class Whiteboard
{
void writeOnBoard()
{
System.out.println("Writing on the whiteboard...");
}
}
// Main class that uses Whiteboard
class Teacher
{
void teachLesson()
{
// Local variable: Dependency created inside the method
Whiteboard board = new Whiteboard();
board.writeOnBoard(); // Temporary usage
System.out.println("Teacher is explaining the topic.");
}
}
// Entry point
public class MainApp
{
public static void main(String[] args)
{
Teacher teacher = new Teacher();
teacher.teachLesson(); // Trigger method that shows dependency
}
}
Writing on the whiteboard... Teacher is explaining the topic.
// Dependent class
class Printer
{
void printDocument()
{
System.out.println("Printing document...");
}
}
// Main class that depends on Printer
class OfficeWorker
{
// Dependency injected via method parameter
void performTask(Printer printer)
{
printer.printDocument(); // Temporary usage
System.out.println("OfficeWorker has completed printing task.");
}
}
// Entry point
public class MainApp
{
public static void main(String[] args)
{
Printer printer = new Printer(); // Create dependency
OfficeWorker worker = new OfficeWorker(); // Create dependent
// Inject dependency via method parameter
worker.performTask(printer);
}
}
Printing document... OfficeWorker has completed printing task.
Feature | Association (HAS-A) | Dependency (USES-A) |
---|---|---|
Duration | Long-term (object is stored) | Temporary (used in a method) |
Object location | Instance variable | Local variable or parameter |
Example | Car has an Engine | OfficeWorker uses a Printer |
Usage | Reused across methods | Used only within one method |
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.