Constructor Injection Example
This program demonstrates constructor based dependency injection.
Problem Statement
Write a Java program to inject dependency Service into Client using constructor.
Source Code
| 1 | class Service { |
| 2 | void serve(){ System.out.println("Service executed"); } |
| 3 | } |
| 4 | class Client { |
| 5 | private Service service; |
| 6 | Client(Service s){ service=s; } |
| 7 | void doWork(){ service.serve(); } |
| 8 | } |
| 9 | public class ConstructorInjection { |
| 10 | public static void main(String[] args) { |
| 11 | System.out.println("Eduinq Constructor Injection"); |
| 12 | Service s=new Service(); |
| 13 | Client c=new Client(s); |
| 14 | c.doWork(); |
| 15 | } |
| 16 | } |
Program Output
Eduinq Constructor Injection Service executed
Explanation
Dependency injection decouples object creation from usage. - Service is injected into Client via constructor. - This makes Client independent of Service instantiation, improving testability and flexibility. - Constructor injection is widely used in frameworks like Spring. Conclusion: Shows how to use constructor based dependency injection.