How do I use composition with inheritance?

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

    Do you have generics in your language? In Java I could do this:

    class Engine {}
    
    abstract class Car 
    {
        private E engine;
        public E getEngine() { return engine; } 
    }
    
    class TurboEngine extends Engine {}
    
    class Ferrari extends Car 
    {
        // Ferrari now has a method with this signature:
        // public TurboEngine getEngine() {} 
    }
    

    I'm sure there's something similar in C#. You can then treat an instance of Ferrari as either an instance of the Ferrari subclass (with getEngine returning the TurboEngine) or as an instance of the Car superclass (when getEngine will return an Engine).

提交回复
热议问题