How do I use composition with inheritance?

前端 未结 10 2389
星月不相逢
星月不相逢 2021-02-09 04:41

I\'m going to try to ask my question in the context of a simple example...

Let\'s say I have an abstract base class Car. Car has-a basic Engine object. I have a method

10条回答
  •  后悔当初
    2021-02-09 05:10

    There's no need to specify a subclass of Car to have a TurboEngine as long as TurboEngine is a subclass of Engine. You can just specify an instance of TurboEngine as the Engine for your Ferrari. You could even put a DieselEngine in your Ferrari. They're all just Engines.

    A Car has an Engine. A TurboEngine is an Engine. A Car can have a TurboEngine or a DieselEngine or a FlintstonesEngine. They're all Engines.

    If you want to limit the type of Engine in your Car subclass (no LawnMowerEngine in a SportsCar), you can leave it declared as Engine and limit it in the setter methods.

    The Car has an Engine relationship doesn't limit the applicable subclasses of Engine.

提交回复
热议问题