What are the signs that code violates the Liskov Substitution Principle?
Subclasses that throw UnsupportedOperationException, override a method to do nothing, or callers that must check instanceof before using a parent-typed object.
Explain it simply
If you need to ask "what kind of object is this really?" before you can use it safely, the subtype is not a true substitute. Other signs: an override that is empty or throws "not supported", or tests written for the parent class that fail when run against the child.
Example
abstract class Bird { abstract void fly(); }
class Sparrow extends Bird {
void fly() { System.out.println("flying"); }
}
class Penguin extends Bird {
void fly() { throw new UnsupportedOperationException(); } // red flag
}
for (Bird b : birds) {
if (!(b instanceof Penguin)) b.fly(); // another red flag
}Fix: do not promise what not every subtype can do.
abstract class Bird { }
interface Flyer { void fly(); }
class Sparrow extends Bird implements Flyer { public void fly() { } }
class Penguin extends Bird { }Now only code that needs flying asks for a Flyer.
What to say in the interview
"Signs are overrides that throw or do nothing, type checks with instanceof, and parent-class tests failing for a child. The fix is usually to split the hierarchy or interface so each type promises only what it can really do."
Common mistakes
- Adding another instanceof check instead of fixing the hierarchy.