KTU OOP Java2024 Scheme • 60M ESE
MODULE 4/Section 1: SOLID Principles in Java

SOLID Principles (Part 2): Liskov Substitution (LSP), Interface Segregation (ISP) & Dependency Inversion (DIP)

HIGH PRIORITY (Prep Guide)Official Syllabus + Supplementary~20 min study
Official KTU 2024 Syllabus Topics Covered Here
Liskov Substitution Principle (LSP)Interface Segregation Principle (ISP)Dependency Inversion Principle (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.

2. Start From Zero: Rubber Duck Trap (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)!

Key Takeaway: LSP = Subclasses must safely replace base classes without surprises; ISP = Split fat interfaces into small role-specific ones; DIP = Depend on interfaces/abstractions, NOT concrete classes.

3. Essential Exam Definitions

Liskov Substitution Principle (LSP)
Introduced by Barbara Liskov: Objects of a superclass must be replaceable with objects of any of its subclasses without breaking the correctness or expected behavioral contract of the program.
Interface Segregation Principle (ISP)
Fourth SOLID principle: No client class should be forced to depend on or implement methods from an interface that it does not use; prefer multiple small cohesive interfaces over one fat monolithic interface.
Dependency Inversion Principle (DIP)
Fifth SOLID principle: (1) High-level modules should not depend on low-level modules; both should depend on abstractions (interfaces). (2) Abstractions should not depend on details; details should depend on abstractions.

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

  1. ISP keeps interfaces tiny and role-specific (MessageChannel).
  2. DIP makes high-level orchestrators (NotificationService) accept those small interfaces via constructors.
  3. LSP guarantees every concrete implementation (EmailSender, SmsSender) honors the contract cleanly without throwing surprises.

6. Examination-Ready Diagrams

Diagram 13

SOLID Principles Overview

S – SRPSingle Responsibility1 reason to changeO – OCPOpen / ClosedExtend via interfacesL – LSPLiskov SubstitutionSubtypes safe swapI – ISPInterface SegregationSmall role interfacesD – DIPDependency InversionDepend on abstractions

Visual summary of Robert C. Martin's five SOLID object-oriented design principles that eliminate rigid, fragile, and tightly coupled code.

Key Components
  • 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.
Step-by-Step Flow
  1. SRP splits mixed responsibilities into cohesive single-purpose classes.
  2. OCP & DIP insert interfaces/abstractions so new features are added via new implementations, not edits.
  3. LSP ensures inheritance hierarchies respect behavioral contracts.
  4. ISP ensures clients only implement methods they actually use.
How to Draw in KTU Exam
  • 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

LSP: Bad (`Ostrich` Breaks `Bird.fly`) vs Good HierarchyLspDesignDemo.java
Shows how extracting FlyingBird preserves substitutability so every FlyingBird passed into makeFly() works reliably.
1// BAD DESIGN (Violates LSP): Ostrich breaks Bird's fly() contract!
2class BadBird {
3 void fly() { System.out.println("Flying..."); }
4}
5class 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
11class Bird {
12 void eat() { System.out.println("Bird is eating seeds."); }
13}
14
15class FlyingBird extends Bird {
16 void fly() { System.out.println("Flying high in the sky!"); }
17}
18
19class Sparrow extends FlyingBird {}
20
21class Ostrich extends Bird {
22 void runFast() { System.out.println("Ostrich running at 60 km/h!"); }
23}
24
25public 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}
Expected Output
Flying high in the sky!
Bird is eating seeds.
Ostrich running at 60 km/h!
Keywords:extends@Override
Common Exam & Coding Mistakes
  • Subclasses throwing UnsupportedOperationException for parent methods they shouldn't have inherited in the first place.
ISP + DIP: Focused Interfaces & Abstraction InjectionIspAndDipDemo.java
Combines ISP (splitting Printable/Scannable) and DIP (OrderNotifier depending on MessageSender abstraction rather than concrete EmailChannel).
1// ISP: Small, cohesive interfaces instead of one fat AllInOneDevice interface
2interface PrinterDevice {
3 void printPage(String text);
4}
5
6interface ScannerDevice {
7 void scanPage();
8}
9
10class 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
18interface MessageChannel {
19 void send(String msg);
20}
21
22class EmailChannel implements MessageChannel {
23 @Override
24 public void send(String msg) {
25 System.out.println("[Email] Sent: " + msg);
26 }
27}
28
29class SmsChannel implements MessageChannel {
30 @Override
31 public void send(String msg) {
32 System.out.println("[SMS] Sent: " + msg);
33 }
34}
35
36class 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
48public 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}
Expected Output
[DeskPrinter] Printing: KTU OOP Revision Sheet
[Email] Sent: ESE starts Monday 9:30 AM
[SMS] Sent: Hall Ticket Released!
Keywords:interfaceimplementsprivatefinal
Common Exam & Coding Mistakes
  • Instantiating new ConcreteLowLevelClass() directly inside a high-level service class (tight coupling violating DIP).

Real-World Applications

  • JDBC itself applies DIP (Connection, Statement, ResultSet are interfaces in java.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 FlyingBird from Bird so Ostrich doesn't break fly()).
  • 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.
Exam Diagram Note: Draw Diagram 13 (SOLID Overview) and include short Bad vs Good comparisons for each principle.

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: