By user702769


2012-10-16 18:49:03 8 Comments

LSP states that classes should be substitutable for their base classes, meaning that derived and base classes should be semantically equivalent.

But does LSP also apply to classes implementing an interface? In other words, if an interface method implemented by a class is semantically different from what user expects it to be, would this be considered as a violation of LSP?

Thank you

2 comments

@supercat 2013-03-07 20:01:09

Yes. Interfaces have an "is an [noun]" relationship just like classes, except that the noun is not a concrete type, but rather a "thing which is [adjective phrase]". If the adjective phrase is "capable of being safely asked if it can accept items, and either capable of accepting items or reporting that it won't", then any object which could not safely be asked if it could accept items, or which might answer yes but then behave badly if actually given an item, would not be a legitimate implementation of the interface described thereby.

@Finglas 2012-10-16 18:51:03

No

It only applies to subtypes. See the Wikipedia article for a brief summary.

If you have a class B that inherits or extends class A you should be able to switch out class A with class B and everything should work as normal. Interfaces are often used in languages that do not allow for multiple inheritance, so while the two objects share a common behaviour, how that actually execute said behaviour is distinct between both, meaning you shouldn't be able to switch them interchangeably.

@user702769 2012-10-16 20:18:58

1 - "It only applies to subtypes." This is first time I hear of the term "subtype". So (in C# at least) a class implementing an interface is not considered a subtype of that interface? 2 - Why ( according to Ray Tayek ) would in Java this be considered a violation of LSP?

@Finglas 2012-10-16 22:08:27

It's a bit fuzzy in terminology. People tend to use subtype/subclass interchangeably. I was referring to an "is a" relationship. That's how I see the LSP, based on inheritance. It would be interesting to hear other points of view however. Regardless, the LSP is just that, a principle. Not a rule. Apply it where required.

@user702769 2012-10-17 10:38:01

much thanx to both of you

Related Questions

Sponsored Content

29 Answered Questions

5 Answered Questions

2 Answered Questions

[SOLVED] Liskov substitution principle and Interface

3 Answered Questions

1 Answered Questions

[SOLVED] Liskov substitution principle

1 Answered Questions

Sponsored Content