Liskov Substitution Principle in Java with Notification Example

🚀 Understanding Liskov Substitution Principle (LSP) with a Simple Java Example One of the most misunderstood SOLID principles is the Liskov Substitution Principle (LSP). 📌 Definition: Subclasses should be replaceable for their base class without altering the correctness of the program. 💻 Example: class Notification { public void sendnot(){ System.out.println("Welcome to the takeUforward"); } } class TextNot extends Notification { public void sendnot() { System.out.println("Welcome to the takeUforward java course"); } } class WhatsAppNot extends Notification { public void sendnot() { System.out.println("Welcome to the takeUforward DSA course"); } } public class TufNot { public static void main(String[] args) { Notification nt = new TextNot(); nt.sendnot(); } } ✅ Why this follows LSP: TextNot and WhatsAppNot can fully replace Notification No unexpected behavior is introduced The program works correctly regardless of which subclass is used ❌ When LSP is violated: If a subclass breaks expected behavior, like: class SilentNotification extends Notification { public void sendnot() { throw new UnsupportedOperationException(); } } Now substituting this class breaks the system 🚨 🧠 Key Insight: Inheritance is not just about reusing code — it's about preserving behavior. 🔥 Takeaway: Always design subclasses so that they extend behavior, not break it. #Java #OOP #SOLID #LSP #SystemDesign #Programming Raj Vikramaditya i understand topic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories