How do I use composition with inheritance?

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

    Depending on your particular language semantics, there are a few ways to do this. Off the cuff my initial thought would be to provide a protected constructor:

    public class Car {
        private Engine engine;
    
        public Car() {
            this(new Engine());
        }
    
        protected Car(Engine engine) {
            this.engine = engine;
        }
    
        public void start() {
            this.engine.start();
        }
    }
    
    public class Ferrari {
        public Ferrari() {
            super(new TurboEngine());
        }
    }
    

提交回复
热议问题