Skip to main content

Command Palette

Search for a command to run...

Dart Inheritance: Prefer Composition over Inheritance

Published
1 min read
Dart Inheritance: Prefer Composition over Inheritance

While inheritance is a powerful concept, it's often recommended to favor composition over inheritance to achieve more flexible and maintainable code. Composition involves building classes by combining simpler classes rather than inheriting from them.


Example

// Composition example
class Engine {
  void start() {
    print('Engine started');
  }
}

class Car {
  Engine _engine = Engine();

  void startCar() {
    _engine.start();
    print('Car started');
  }
}

void main() {
  Car myCar = Car();
  myCar.startCar();
}

In this example, the Car class has a composition relationship with the Engine class. Instead of inheriting from Engine, a Car contains an instance of Engine and delegates the start functionality. This allows for better code reuse and flexibility.

When composing classes, changes in one component don't affect others as much compared to a deep inheritance hierarchy.

Dart

Part 38 of 50

I'll be here to provide explanations, examples, and assistance as you explore the depths of Dart programming language. Together, we'll unravel the intricacies of Dart, from its fundamental concepts to

Up next

Dart Inheritance: Checking an Objects Type at runtime

Dart provides the is and as operators for checking an object's type at runtime. This is useful when you need to perform different actions based on the actual type of an object. isoperator The is operator allows you to check if an object belongs to a ...

More from this blog

Flutter Journey with Jinali

141 posts