开发者

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

开发者 https://www.devze.com 2022-12-19 20:50 出处:网络
loosely speaking, Liskov Substitution Principle states that a derived class can be substitute in place of the base class without affecting the user.

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 t开发者_StackOverflowhe base class, does the Liskov inheritance restrictions still apply to the derived class?


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.


Yes, because a caller can always do this:

BaseAbstractClass instance = new DerivedClass();


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号