Single Responsibility Principle
This program demonstrates Single Responsibility Principle.
Problem Statement
Write a Java program where InvoicePrinter only handles printing, not calculation.
Source Code
| 1 | class Invoice { |
| 2 | double amount; |
| 3 | Invoice(double amt){ amount=amt; } |
| 4 | } |
| 5 | class InvoicePrinter { |
| 6 | void print(Invoice inv){ System.out.println("Invoice amount: "+inv.amount); } |
| 7 | } |
| 8 | public class SRPExample { |
| 9 | public static void main(String[] args) { |
| 10 | System.out.println("Eduinq SRP Example"); |
| 11 | Invoice inv=new Invoice(500); |
| 12 | InvoicePrinter ip=new InvoicePrinter(); |
| 13 | ip.print(inv); |
| 14 | } |
| 15 | } |
Program Output
Eduinq SRP Example Invoice amount: 500.0
Explanation
SRP states a class should have only one reason to change. - Invoice holds data, InvoicePrinter handles printing. - Separation improves maintainability and clarity. Conclusion: Shows how to apply Single Responsibility Principle.