SOLID Principles (Part 2): Liskov Substitution (LSP), Interface Segregation (ISP) & Dependency Inversion (DIP)
1. Topic Introduction
The remaining three SOLID principles ensure your inheritance trees don't lie (LSP), your interfaces don't force unused dummy methods (ISP), and your high-level business logic doesn't lock itself onto concrete hardware/database classes (DIP). Together with SRP and OCP, these complete Section 1 of Module 4.
LSP), Menu Card Split (ISP) & Universal Wall Socket (DIP)1. LSP (Liskov Substitution): If Bird promises fly(), making Ostrich extends Bird and throwing an exception inside fly() breaks anyone expecting every Bird to fly! Only group Sparrow under FlyingBird.
2. ISP (Interface Segregation): Don't hand a vegetarian customer a 20-page restaurant interface forcing them to implement cookSteak(). Split fat interfaces into small focused menus (VegMenu, NonVegMenu or Printer, Scanner).
3. DIP (Dependency Inversion): Soldering a lamp directly into house wall wires makes changing lamps impossible. Install a standard electrical socket (interface Switchable) so your wall switch (high-level) depends on the socket abstraction—never directly on a specific PhilipsBulb (low-level)!
3. Essential Exam Definitions
4. Detailed Technical Explanation & Syntax
1. Liskov Substitution Principle (LSP)
Why Needed: Naive inheritance creates bugs when a subclass violates the base class's behavioral promise (classic examples: Ostrich extends Bird failing fly(), or Square extends Rectangle breaking setWidth/setHeight independence).
Bad vs Good Design: In Bad Design, Bird has fly() and Ostrich throws UnsupportedOperationException. In Good Design, Bird defines eat(), and a separate FlyingBird extends Bird adds fly(), so Sparrow extends FlyingBird while Ostrich extends Bird.
Advantages: Safe runtime polymorphism, trustworthy IS-A hierarchies, zero unexpected exceptions during substitution.
2. Interface Segregation Principle (ISP)
Why Needed: A bloated interface Worker { void work(); void eatLunch(); } or SmartMachine { print(); scan(); fax(); } forces a RobotWorker or SimplePrinter to write empty/dummy or exception-throwing methods (fax()).
Bad vs Good Design: Split SmartMachine into granular role interfaces: Printable, Scannable, Faxable. A BasicPrinter implements ONLY Printable, while an AllInOnePrinter implements all three.
Advantages: Zero dummy/stub code, decoupled clients, higher cohesion.
3. Dependency Inversion Principle (DIP)
Why Needed: In Bad Design, high-level NotificationService directly creates new EmailSender() inside itself (private EmailSender sender = new EmailSender();). Switching to SMS/WhatsApp requires editing NotificationService directly!
Bad vs Good Design: Define interface MessageChannel { void send(String msg); }. Both EmailSender and SmsSender implement MessageChannel. NotificationService receives a MessageChannel via constructor injection (Dependency Injection), inverting the dependency!
Advantages: High-level business rules stay decoupled from volatile low-level implementations, making testing (mocking) and swapping components effortless.
5. Working Principle: How LSP, ISP & DIP Fit Together
- ISP keeps interfaces tiny and role-specific (
MessageChannel). - DIP makes high-level orchestrators (
NotificationService) accept those small interfaces via constructors. - LSP guarantees every concrete implementation (
EmailSender,SmsSender) honors the contract cleanly without throwing surprises.
6. Examination-Ready Diagrams
SOLID Principles Overview
Visual summary of Robert C. Martin's five SOLID object-oriented design principles that eliminate rigid, fragile, and tightly coupled code.
- S – Single Responsibility: A class should have only one reason to change.
- O – Open/Closed: Open for extension, closed for modification.
- L – Liskov Substitution: Subtypes must be substitutable for their base types without breaking behavior.
- I – Interface Segregation: Prefer small, focused interfaces over fat monolithic interfaces.
- D – Dependency Inversion: High-level modules depend on abstractions, not concrete low-level classes.
- SRP splits mixed responsibilities into cohesive single-purpose classes.
- OCP & DIP insert interfaces/abstractions so new features are added via new implementations, not edits.
- LSP ensures inheritance hierarchies respect behavioral contracts.
- ISP ensures clients only implement methods they actually use.
- Draw 5 vertical pillars or stacked blocks labeled S, O, L, I, D with the exact 1-line definition and Java mechanism (
Split classes,Interface/Polymorphism,Safe Subtyping,Small Interfaces,Inject Abstractions).
7. Complete Java Code Examples & Tracing
FlyingBird preserves substitutability so every FlyingBird passed into makeFly() works reliably.| 1 | // BAD DESIGN (Violates LSP): Ostrich breaks Bird's fly() contract! |
| 2 | class BadBird { |
| 3 | void fly() { System.out.println("Flying..."); } |
| 4 | } |
| 5 | class BadOstrich extends BadBird { |
| 6 | @Override |
| 7 | void fly() { throw new UnsupportedOperationException("Ostriches cannot fly!"); } |
| 8 | } |
| 9 | |
| 10 | // GOOD DESIGN (Follows LSP): Separate flying capability cleanly |
| 11 | class Bird { |
| 12 | void eat() { System.out.println("Bird is eating seeds."); } |
| 13 | } |
| 14 | |
| 15 | class FlyingBird extends Bird { |
| 16 | void fly() { System.out.println("Flying high in the sky!"); } |
| 17 | } |
| 18 | |
| 19 | class Sparrow extends FlyingBird {} |
| 20 | |
| 21 | class Ostrich extends Bird { |
| 22 | void runFast() { System.out.println("Ostrich running at 60 km/h!"); } |
| 23 | } |
| 24 | |
| 25 | public class LspDesignDemo { |
| 26 | static void letItFly(FlyingBird fb) { |
| 27 | fb.fly(); // Guaranteed safe substitution for ANY FlyingBird! |
| 28 | } |
| 29 | |
| 30 | public static void main(String[] args) { |
| 31 | letItFly(new Sparrow()); |
| 32 | Ostrich ostrich = new Ostrich(); |
| 33 | ostrich.eat(); |
| 34 | ostrich.runFast(); |
| 35 | } |
| 36 | } |
Flying high in the sky! Bird is eating seeds. Ostrich running at 60 km/h!
extends@Override- Subclasses throwing
UnsupportedOperationExceptionfor parent methods they shouldn't have inherited in the first place.
Printable/Scannable) and DIP (OrderNotifier depending on MessageSender abstraction rather than concrete EmailChannel).| 1 | // ISP: Small, cohesive interfaces instead of one fat AllInOneDevice interface |
| 2 | interface PrinterDevice { |
| 3 | void printPage(String text); |
| 4 | } |
| 5 | |
| 6 | interface ScannerDevice { |
| 7 | void scanPage(); |
| 8 | } |
| 9 | |
| 10 | class DeskPrinter implements PrinterDevice { // Not forced to implement scanPage()! |
| 11 | @Override |
| 12 | public void printPage(String text) { |
| 13 | System.out.println("[DeskPrinter] Printing: " + text); |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | // DIP: High-level module depends on abstraction, NOT concrete low-level class |
| 18 | interface MessageChannel { |
| 19 | void send(String msg); |
| 20 | } |
| 21 | |
| 22 | class EmailChannel implements MessageChannel { |
| 23 | @Override |
| 24 | public void send(String msg) { |
| 25 | System.out.println("[Email] Sent: " + msg); |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | class SmsChannel implements MessageChannel { |
| 30 | @Override |
| 31 | public void send(String msg) { |
| 32 | System.out.println("[SMS] Sent: " + msg); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | class ExamAlertService { // High-level module |
| 37 | private final MessageChannel channel; // Depends on abstraction! |
| 38 | |
| 39 | ExamAlertService(MessageChannel channel) { // Dependency Injection |
| 40 | this.channel = channel; |
| 41 | } |
| 42 | |
| 43 | void publishTimetable(String info) { |
| 44 | channel.send(info); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | public class IspAndDipDemo { |
| 49 | public static void main(String[] args) { |
| 50 | PrinterDevice p = new DeskPrinter(); |
| 51 | p.printPage("KTU OOP Revision Sheet"); |
| 52 | |
| 53 | ExamAlertService emailAlerts = new ExamAlertService(new EmailChannel()); |
| 54 | emailAlerts.publishTimetable("ESE starts Monday 9:30 AM"); |
| 55 | |
| 56 | ExamAlertService smsAlerts = new ExamAlertService(new SmsChannel()); |
| 57 | smsAlerts.publishTimetable("Hall Ticket Released!"); |
| 58 | } |
| 59 | } |
[DeskPrinter] Printing: KTU OOP Revision Sheet [Email] Sent: ESE starts Monday 9:30 AM [SMS] Sent: Hall Ticket Released!
interfaceimplementsprivatefinal- Instantiating
new ConcreteLowLevelClass()directly inside a high-level service class (tight coupling violating DIP).
Real-World Applications
- JDBC itself applies DIP (
Connection,Statement,ResultSetare interfaces injava.sql; vendor drivers plug in underneath!). - Java's Listener interfaces (
ActionListener,MouseListener,KeyListener) follow ISP instead of forcing one gigantic 20-method listener.
Important KTU Exam Points
- Memorize all 5 SOLID expansions + 1-line definitions + Bad vs Good Java code examples.
- Notice how JDBC and Swing Listeners connect directly back to DIP and ISP—great bonus insight for 9-mark answers!
Memory Techniques & Revision
- S-O-L-I-D: Single reason | Open/Closed | Liskov safe swap | Interface small | Depend on abstractions.
Common Pitfalls to Avoid
- Confusing DIP (Dependency Inversion Principle = depend on abstractions) with Dependency Injection (the technique of passing dependencies via constructor/setter to achieve DIP).
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
Introduction: LSP, ISP, and DIP ensure safe inheritance hierarchies, clean focused interfaces, and decoupled high-level architectures in Java.
- LSP (Liskov Substitution): Subclasses must safely substitute their superclasses without breaking expected behavior (e.g., separate
FlyingBirdfromBirdsoOstrichdoesn't breakfly()). - ISP (Interface Segregation): Clients should not be forced to implement unused methods; split bloated interfaces into small role-specific ones (
PrinterDevice,ScannerDevice). - DIP (Dependency Inversion): High-level modules should depend on abstractions (
MessageChannel) rather than concrete low-level classes (EmailChannel), enabling plug-and-play swapping.
Quick Understanding Check
1. A SimplePrinter class implements a MultiFunctionDevice interface and leaves scan() and fax() throwing errors. Which principle is violated?
2. Under Dependency Inversion Principle (DIP), both high-level and low-level modules should depend on: