Interface Segregation Principle
This program demonstrates Interface Segregation Principle.
Problem Statement
Write a Java program where clients only implement methods they need.
Source Code
| 1 | interface Printer { void print(); } |
| 2 | interface Scanner { void scan(); } |
| 3 | class SimplePrinter implements Printer { |
| 4 | public void print(){ System.out.println("Printing document"); } |
| 5 | } |
| 6 | public class ISPExample { |
| 7 | public static void main(String[] args) { |
| 8 | System.out.println("Eduinq ISP Example"); |
| 9 | Printer p=new SimplePrinter(); |
| 10 | p.print(); |
| 11 | } |
| 12 | } |
Program Output
Eduinq ISP Example Printing document
Explanation
ISP states clients should not be forced to implement unnecessary methods. - Separate interfaces for Printer and Scanner. - SimplePrinter only implements Printer, avoiding unused methods. Conclusion: Shows how to apply Interface Segregation Principle.