🚫Issue in the Hierarchy (Why it Violates LSP?)
Liskov Substitution Principle (LSP) states that a subclass should be substitutable for its base class without breaking functionality.
- Here,
Penguin
inherits thefly()
method fromBird
, but penguins cannot fly in reality. - If we use a
Penguin
object in place of aBird
and callfly()
, it will produce incorrect behavior. - This violates LSP because not all
Birds
can fly, butBird
assumes that all of its subclasses will supportfly()
.
✅How the Refactored Code Follows LSP
- Created an abstract
Bird
classBird
no longer assumes all birds can fly. Instead, it has a genericmove()
method.Penguin
andParrot
both extendBird
, but each defines movement appropriately.
- Introduced a
CanFly
Interface- Only birds that can actually fly (like
Parrot
) implement theCanFly
interface. Penguin
does not implementCanFly
, so it never has an incorrectfly()
method .
- Only birds that can actually fly (like
🔹Summary of Fixes
Problem | Before Refactoring | After Refactoring |
---|---|---|
LSP Violation | Penguin extends Bird but inherits fly() , which it shouldn't. |
Bird class no longer assumes all birds fly .CanFly interface is introduced. |
Incorrect Behavior | Calling penguin.fly() is logically incorrect. |
Penguinsdo not have a fly() method , preventing misuse. |
Better Code Structure | One big class with misleading behavior. | A properhierarchy using abstraction & interfaces . |
-> Final Benefits
✅ Ensures correct behavior – Penguin
never has an invalid fly()
method.
✅ Follows LSP – Substituting Penguin
or Parrot
for Bird
does not break functionality.
✅ Easier to extend – We can add more bird types without modifying existing code.
This approach ensures maintainability, correctness, and compliance with Liskov’s Substitution Principle !