A.A.
A.A.

Reputation: 147

Does the Liskov Substitution Principle apply to subtype which inherited from abstract class?

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?

Upvotes: 13

Views: 3210

Answers (4)

lance
lance

Reputation: 16342

Yes.

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

Source: the Old Articles page of cleancoder.com

Upvotes: -1

Jeff Sternal
Jeff Sternal

Reputation: 48623

Yes, because a caller can always do this:

BaseAbstractClass instance = new DerivedClass();

Upvotes: 0

David Gladfelter
David Gladfelter

Reputation: 4213

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.

Upvotes: -1

tvanfosson
tvanfosson

Reputation: 532605

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.

Upvotes: 7

Related Questions