Deriving an abstract class from concrete class

后端 未结 7 822
囚心锁ツ
囚心锁ツ 2021-02-05 16:05

Let\'s say we have a concrete class Apple. (Apple objects can be instantiated.) Now, someone comes and derives an abstract class Peach from Apple. It\'

7条回答
  •  说谎
    说谎 (楼主)
    2021-02-05 16:51

    If you use the recommended practice of having inheritance model "is-a" then this pattern would pretty much never come up.

    Once you have a concrete class, you are saying that it is something that you can actually create an instance of. If you then derive an abstract class from it, then something that is an attribute of the base class is not true of the derived class, which should set of klaxons that something's not right.

    Looking at your example, a peach is not an apple, so it should not be derived from it. Same is true for Tomato deriving from Berry.

    This is where I would usually advise containment, but that doesn't even seem to be a good model, since an Apple does not contain a Peach.

    In this case, I would factor out the common interface -- PieFilling or DessertItem.

提交回复
热议问题