How do I use composition with inheritance?

前端 未结 10 2383
星月不相逢
星月不相逢 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:30

    As I understand your (updated) question, you're going to have to cast the car's engine to the TurboEngine type if you want to call TurboEngine methods on it. That results in a lot of checking to see if the car you have has a TurboEngine before you call those methods, but that's what you get. Not knowing what this car is actually standing in for, I can't think of any reason you couldn't have the engine and the turbo engine share the same interface - are there really new methods that the turbo supports, or does it just do the same things differently - but I guess this metaphor was going to fall apart sooner or later.

提交回复
热议问题