Dependency Inversion Principle

This program demonstrates Dependency Inversion Principle.

Problem Statement

Write a Java program where high level module depends on abstraction, not concrete class.

Source Code

1 interface Service { void serve(); }
2 class ServiceImpl implements Service {
3 public void serve(){ System.out.println("Service executed"); }
4 }
5 class Client {
6 private Service service;
7 Client(Service s){ service=s; }
8 void doWork(){ service.serve(); }
9 }
10 public class DIPExample {
11 public static void main(String[] args) {
12 System.out.println("Eduinq DIP Example");
13 Service s=new ServiceImpl();
14 Client c=new Client(s);
15 c.doWork();
16 }
17 }

Program Output

Eduinq DIP Example
Service executed

Explanation

DIP states high level modules should depend on abstractions. - Client depends on Service interface, not ServiceImpl. - This promotes loose coupling and flexibility. Conclusion: Shows how to apply Dependency Inversion Principle.

Quick Links to Explore