How do I use composition with inheritance?

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

    You can always use an abstract that is protected. The public "Start" will call the protected (that will be ovveride in the abstract class). This way the caller only see the Start() and not the StartEngine().

    abstract class Car {
        private Engine engine;
    
        public Car() {
            this.engine = new Engine();
        }
    
        protected Car(Engine engine) {
            this.engine = engine;
        }
    
        public void Start()
        {
            this.StartEngine();
        }
        protected abstract void StartEngine();
    }
    
    public class Ferrari : Car
    {
        public Ferrari() {
    
        }
        protected override void StartEngine()
        {
            Console.WriteLine("TURBO ENABLE!!!");
        }
    
    }
    

    -The way to use it:

    Car c = new Ferrari();
    c.Start();
    

提交回复
热议问题