Interface Injection Example
This program demonstrates interface based dependency injection.
Problem Statement
Write a Java program to inject dependency using interface method.
Source Code
| 1 | interface Service { |
| 2 | void serve(); |
| 3 | } |
| 4 | class ServiceImpl implements Service { |
| 5 | public void serve(){ System.out.println("Service executed"); } |
| 6 | } |
| 7 | interface Consumer { |
| 8 | void setService(Service s); |
| 9 | } |
| 10 | class Client implements Consumer { |
| 11 | private Service service; |
| 12 | public void setService(Service s){ service=s; } |
| 13 | void doWork(){ service.serve(); } |
| 14 | } |
| 15 | public class InterfaceInjection { |
| 16 | public static void main(String[] args) { |
| 17 | System.out.println("Eduinq Interface Injection"); |
| 18 | Service s=new ServiceImpl(); |
| 19 | Client c=new Client(); |
| 20 | c.setService(s); |
| 21 | c.doWork(); |
| 22 | } |
| 23 | } |
Program Output
Eduinq Interface Injection Service executed
Explanation
Interface defines contract for injecting dependency. - Client implements Consumer interface to accept Service. - This promotes loose coupling and flexibility, allowing different services to be injected. - Interface injection is less common but demonstrates extensibility. Conclusion: Shows how to use interface based dependency injection.