Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Composition vs Inheritance | Composition, Inheritance, and Refactoring
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
C# OOP Class Construction Drills

bookComposition vs Inheritance

Understanding how to build complex objects from simpler ones is a key part of object-oriented programming. Two fundamental approaches are composition and inheritance. Imagine a car: it is made up of many parts, including an engine, wheels, and seats. This is composition—building something by combining other objects. Inheritance, on the other hand, is like a family tree: a dog is a kind of animal, so it inherits the basic characteristics of animals but also has its own unique features. Both approaches help you organize code and reuse logic, but they serve different purposes in class design.

Note
Definition

Composition: building complex objects by combining simpler ones, where one class contains instances of other classes.

Inheritance: creating new classes based on existing ones, inheriting their properties and methods.

Program.cs

Program.cs

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
using System; namespace ConsoleApp { public class Engine { public int HorsePower { get; set; } public Engine(int horsePower) { HorsePower = horsePower; } public void Start() { Console.WriteLine("Engine started with " + HorsePower + " HP."); } } public class Car { public Engine Engine { get; set; } public string Model { get; set; } public Car(string model, Engine engine) { Model = model; Engine = engine; } public void StartCar() { Console.WriteLine("Starting car: " + Model); Engine.Start(); } } public class Program { public static void Main(string[] args) { Engine myEngine = new Engine(200); Car myCar = new Car("Sedan", myEngine); myCar.StartCar(); } } }

In the example above, the Car class contains an Engine object as a property. This is an example of composition: a car "has an" engine. The Car delegates the responsibility of starting the engine to its Engine object. This approach allows you to change the engine without changing how the car works as a whole, and lets you reuse the Engine class in other contexts, such as a boat or a generator.

Composition is flexible and encourages loose coupling between classes:

  • You can swap out or modify the Engine without rewriting the Car class;
  • The same Engine class can be used in multiple different objects;
  • Each class focuses on its own responsibility, making your code easier to maintain and extend.
Animals.cs

Animals.cs

copy
123456789101112131415161718192021
namespace ConsoleApp { // Base class public class Animal { public string Name { get; set; } public void Eat() { // Eating behavior } } // Derived class public class Dog : Animal { public void Bark() { // Barking behavior } } }

When you use inheritance, you create a new class that is a specialized version of an existing class. In the code above, Dog is a subclass of Animal. This means every Dog is an Animal and inherits its properties and methods. Inheritance is useful when you have a clear "is a" relationship, such as a dog being an animal.

However, you should be careful with inheritance, as it can make code harder to maintain if used inappropriately. Composition is often preferred when you want to build complex types from simpler, reusable components. Choose inheritance when you need to extend or specialize behavior, and composition when you want to combine behaviors or delegate responsibilities.

1. What is composition in object-oriented programming?

2. When might inheritance be a better choice than composition?

3. What is a potential drawback of deep inheritance hierarchies?

question mark

What is composition in object-oriented programming?

Select the correct answer

question mark

When might inheritance be a better choice than composition?

Select the correct answer

question mark

What is a potential drawback of deep inheritance hierarchies?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 1

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

bookComposition vs Inheritance

Deslize para mostrar o menu

Understanding how to build complex objects from simpler ones is a key part of object-oriented programming. Two fundamental approaches are composition and inheritance. Imagine a car: it is made up of many parts, including an engine, wheels, and seats. This is composition—building something by combining other objects. Inheritance, on the other hand, is like a family tree: a dog is a kind of animal, so it inherits the basic characteristics of animals but also has its own unique features. Both approaches help you organize code and reuse logic, but they serve different purposes in class design.

Note
Definition

Composition: building complex objects by combining simpler ones, where one class contains instances of other classes.

Inheritance: creating new classes based on existing ones, inheriting their properties and methods.

Program.cs

Program.cs

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
using System; namespace ConsoleApp { public class Engine { public int HorsePower { get; set; } public Engine(int horsePower) { HorsePower = horsePower; } public void Start() { Console.WriteLine("Engine started with " + HorsePower + " HP."); } } public class Car { public Engine Engine { get; set; } public string Model { get; set; } public Car(string model, Engine engine) { Model = model; Engine = engine; } public void StartCar() { Console.WriteLine("Starting car: " + Model); Engine.Start(); } } public class Program { public static void Main(string[] args) { Engine myEngine = new Engine(200); Car myCar = new Car("Sedan", myEngine); myCar.StartCar(); } } }

In the example above, the Car class contains an Engine object as a property. This is an example of composition: a car "has an" engine. The Car delegates the responsibility of starting the engine to its Engine object. This approach allows you to change the engine without changing how the car works as a whole, and lets you reuse the Engine class in other contexts, such as a boat or a generator.

Composition is flexible and encourages loose coupling between classes:

  • You can swap out or modify the Engine without rewriting the Car class;
  • The same Engine class can be used in multiple different objects;
  • Each class focuses on its own responsibility, making your code easier to maintain and extend.
Animals.cs

Animals.cs

copy
123456789101112131415161718192021
namespace ConsoleApp { // Base class public class Animal { public string Name { get; set; } public void Eat() { // Eating behavior } } // Derived class public class Dog : Animal { public void Bark() { // Barking behavior } } }

When you use inheritance, you create a new class that is a specialized version of an existing class. In the code above, Dog is a subclass of Animal. This means every Dog is an Animal and inherits its properties and methods. Inheritance is useful when you have a clear "is a" relationship, such as a dog being an animal.

However, you should be careful with inheritance, as it can make code harder to maintain if used inappropriately. Composition is often preferred when you want to build complex types from simpler, reusable components. Choose inheritance when you need to extend or specialize behavior, and composition when you want to combine behaviors or delegate responsibilities.

1. What is composition in object-oriented programming?

2. When might inheritance be a better choice than composition?

3. What is a potential drawback of deep inheritance hierarchies?

question mark

What is composition in object-oriented programming?

Select the correct answer

question mark

When might inheritance be a better choice than composition?

Select the correct answer

question mark

What is a potential drawback of deep inheritance hierarchies?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 1
some-alt