views:

89

answers:

5

loosely speaking, Liskov Substitution Principle states that a derived class can be substitute in place of the base class without affecting the user. In the case when the base class is an abstract class, which means no user is using an instance of the base class, does the Liskov inheritance restrictions still apply to the derived class?

A: 

Yes, because a caller can always do this:

BaseAbstractClass instance = new DerivedClass();
Jeff Sternal
+1  A: 

Just because you can't instantiate a particular class does not mean that you can't use it. In this scenario, the calling code is using the abstract base class as the definition of the contract under which it operates. In that sense, every class that derives from the base class ought to be interchangable with respect to the interface defined by the base class, so yes Liskov still applies. In fact, this is one primary reason why you would want to have an abstract base class for a collection of classes that have some common behavior -- so you can define operations in terms of the base class interface and not care about which derived class that you are actually operating on.

tvanfosson
A: 

Abstract classes do not conflict with LSP at all. Many people consider using "new" directly from the client code to be a violation of the spirit of LSP. If you both instantiate and use an object, you're tightly-bound to that implementation, and you can't "substitute" it at all.

Consider having the object created via a factory or passed in as an argument or via dependency injection after being created by some kind of repository that can be focused on making decisions about what concrete types are needed in various circumstances.

David Gladfelter
A: 

In short, yes. The LSP applies to essentially all public inheritance. The fact that a base class is abstract doesn't change that. The base class defines an interface, and all legitimate derivatives must satisfy all the requirements of that interface.

Jerry Coffin
A: 

Yes.

See the "A Real Example" section (page 7-8) of Uncle Bob's The Liskov Substitution Principle article.

lance