0

In short, Liskov's Substitution Principle states that instances of the base (super) class should be completely replaceable with instances its derived (sub) classes without introducing any "breaking code" like throwing new errors, changing the contract of the methods, etc.

This means java.lang.Object should be replaceable with instances of any of its subclasses everywhere. However, every class is a subtype of Object.

I can instantiate a class say, for example, NetworkAdapter and pass it as an Object and according to LSP, I should be able to cast that Object instance into a random subclass, say Foo? However, NetworkAdapter and Foo are completely incompatible with each other.

NetworkAdapter nA = new NetworkAdapter(); Object obj = (Object) nA; // completely okay and legal Foo foo = (Foo) obj; // ??? this would throw ClassCastException! 

Am I understanding LSP wrong? Or does the structure of the Java language violate LSP in some cases?

3
  • You did not demonstrate "replacing" any object. "Replacing" a superclass object with a subclass object means actually changing the source code. In order to demonstrate the LSP, you should show two versions of your code, before and after the replacement. Commented Sep 10, 2020 at 5:08
  • Okay so if I understand correctly, LSP isn't about "casts"? It's about the actual replacement of the instance of the superclass with one of the subclasses' instances and still be valid, right? Commented Sep 10, 2020 at 5:19
  • 1
    Correct. It's not about casts. Commented Sep 10, 2020 at 5:21

1 Answer 1

1

If you want to think about the LSP in terms of casting, it would be concerned with upcasting rather than downcasting.

Can you safely pass NetworkAdapter to a method that accepts Object or does the subclass violate the contract of the parent? Violations of the Object contract would include incorrectly implementing equals and hashCode.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.