Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 286
A.A. Avatar asked Feb 12 '10 19:02

A.A.


People also ask

What are the behavioral conditions that a subtype must meet in the Liskov Substitution Principle?

The Liskov Substitution Principle in practical software development. The principle defines that objects of a superclass shall be replaceable with objects of its subclasses without breaking the application. That requires the objects of your subclasses to behave in the same way as the objects of your superclass.

Where we use Liskov Substitution Principle?

The Liskov Substitution Principle helps us model good inheritance hierarchies. It helps us prevent model hierarchies that don't conform to the Open/Closed principle. Any inheritance model that adheres to the Liskov Substitution Principle will implicitly follow the Open/Closed principle.

Can you inherit from an abstract class?

An abstract class cannot be inherited by structures. It can contain constructors or destructors. It can implement functions with non-Abstract methods. It cannot support multiple inheritances.

Does Liskov Substitution Principle apply to interfaces?

LSP applies to the contract. The contract may be a class or an interface.


2 Answers

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.

like image 154
tvanfosson Avatar answered Sep 28 '22 02:09

tvanfosson


Yes, because a caller can always do this:

BaseAbstractClass instance = new DerivedClass();
like image 20
Jeff Sternal Avatar answered Sep 28 '22 00:09

Jeff Sternal