Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Composition vs Inheritance | Composition and Polymorphism
/
Dart OOP Essentials

bookComposition vs Inheritance

メニューを表示するにはスワイプしてください

Note
Definition

Composition is an object-oriented design principle where a class contains other objects and uses them to perform its work instead of inheriting their behavior.

Composition helps you build complex features by combining simpler classes rather than extending a single parent class. In Dart, this means storing instances of other classes as fields and delegating responsibilities to them. Compared to inheritance, composition reduces tight coupling, improves flexibility, and makes your code easier to test and maintain.

'Has-a' vs 'Is-a' relationships
expand arrow
  • Inheritance models an "is-a" relationship: a Dog is an Animal.
  • Composition models a "has-a" relationship: a Car has an Engine.
main.dart

main.dart

copy
123456789101112131415161718192021
class Engine { void start() { print('Engine started'); } } class Car { final Engine engine; Car(this.engine); void start() { engine.start(); } } void main() { Engine myEngine = Engine(); Car myCar = Car(myEngine); myCar.start(); // Output: Engine started }

In this example, the Car class does not inherit from Engine. Instead, it holds an instance of Engine and delegates the start() action to it. This is a classic use of composition: Car has-an Engine, and can use its functionality without forming a rigid inheritance relationship. You should prefer composition over inheritance when you want to use features from another class but do not want to expose your class to all behaviors of the parent, or when you want to change the implementation details without affecting a class hierarchy.

main.dart

main.dart

copy
123456789101112131415161718192021
class Screen { void display() { print('Screen is displaying content'); } } class Phone { final Screen screen; Phone(this.screen); void showHomeScreen() { screen.display(); } } void main() { Screen phoneScreen = Screen(); Phone myPhone = Phone(phoneScreen); myPhone.showHomeScreen(); // Output: Screen is displaying content }
Note
Note

Favoring composition over inheritance means designing your classes to include (compose) other objects to share functionality, rather than always extending classes. This leads to more flexible, maintainable, and reusable code.

question mark

In which scenario is composition preferred over inheritance in Dart?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  1
some-alt