Dart Inheritance : Prefer Composition over Inheritance

Dart Inheritance : Prefer Composition over Inheritance

·

1 min read

Prefer Composition over inheritance :

  • A favour composition over inheritance to achieve more flexible and maintainable code.

    • Example :

    •   // Composition example
        class Engine {
          void start() {
            print('Engine started');
          }
        }
      
        class Car {
          final Engine _engine = Engine();
      
          void startCar() {
            _engine.start();
            print('Car started');
          }
        }
      
        void main() {
          Car myCar = Car();
          myCar.startCar();
        }
      
    •   Engine started
        Car started
      
        Exited.