Loose Coupling Example
This program demonstrates loose coupling.
Problem Statement
Write a Java program where Client depends on interface, 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 LooseCoupling { |
| 11 | public static void main(String[] args) { |
| 12 | System.out.println("Eduinq Loose Coupling"); |
| 13 | Service s=new ServiceImpl(); |
| 14 | Client c=new Client(s); |
| 15 | c.doWork(); |
| 16 | } |
| 17 | } |
Program Output
Eduinq Loose Coupling Service executed
Explanation
Loose coupling reduces dependency between classes. - Client depends on Service interface, not implementation. - This improves flexibility and testability. Conclusion: Shows how to design loose coupling.