1. Introduction
In object-oriented programming,composition is a design principle that allows us to model real-world relationships in our programs. Instead of inheriting properties from another class, we embed an instance of another class within our class. In this post, we'll examine composition through a classic example: the relationship between aCar and itsEngine.
Definition
Composition is a principle where a class embeds or references another class's objects, thus allowing it to utilize the functionalities and properties of the embedded class. The key characteristic of composition is the phrase "has a." In our example, aCar "has an"Engine.
2. Program Steps
1. Define anEngine class that represents the basic functionalities of an engine.
2. Define aCar class that will contain an instance of theEngine class.
3. Provide methods in theCar class to interact with and showcase theEngine's functionalities.
3. Code Program
# Define the Engine classclass Engine def start "Engine started!" end def stop "Engine stopped!" endend# Define the Car classclass Car def initialize @engine = Engine.new end def start @engine.start + " Car is ready to drive!" end def stop @engine.stop + " Car is parked!" endend# Instantiate a car and interact with itmy_car = Car.newputs my_car.startputs my_car.stopOutput:
Engine started! Car is ready to drive!Engine stopped! Car is parked!
Explanation:
1. We first create anEngine class that has basic methods tostart andstop an engine.
2. Next, we define theCar class. Instead of inheriting properties and methods from theEngine class, we embed an instance of theEngine class inside theCar class. This is done using the@engine = Engine.new line in theCar's constructor.
3. In theCar class, we havestart andstop methods that call the respective methods of the embeddedEngine object and append some additional behavior specific to theCar.
4. When we instantiate aCar object and call its methods, the output demonstrates the combined behavior of theCar and itsEngine.
This implementation demonstrates how composition can be a powerful tool to model real-world relationships in code, allowing classes to have and utilize functionalities of other classes without resorting to inheritance.
Comments
Post a Comment