Lesson 05 Composition
Lesson 05 Composition
Composition
• Composition is one of the important concepts
of Object-oriented programming (OOP)
• Composition basically enables us for creating
complex types objects by combining other
types of objects in the program.
• Composition provides Reusability of the code.
Composition
• It models the relationship between two
classes
• Composition involves using other classes to
build more complex classes. Basically, complex
objects are composed of other objects.
• Composition represents a has-a relationship
Has-a-relationship
• Consider the computer as an object.
Computer has-a motherboard, keyboard, hard
disk, etc. Composed objects also can be
composed of other objects. For example,
motherboard has-a RAM, CPU, etc.
Has-a-relationship
• It means that a composite class present in the
program can contains the objects from the
other class components and this type of
relationship model is called as has a
relationship.
Composite Vs Component
• The classes that contains objects from the
other classes in the program are called as
composites whereas the classes which we use
to create more complex type of relationship
models is called as components.
Composite Vs Component
Examples
Examples
• The class has a teacher
• Zoo has a lion
• The bike has an engine
• It represents part of the relationship
• Use Composition, when an object contains
other objects, and the contained object can’t
exist without other objects.
UML
Class Activity
• Give examples for Composition in daily life.
Important Points
• It defines a strong type of relationship (Has-a).
• It can be defined as when a class can
reference one or more objects of another
class inside its instance variable.
• In composition, objects can not exist
independently.
Composition in Python
Composition in Python
Another Example
Another Example(cont’d)
Example
Example (cont’d)
Example (cont’d)
Example Output
When to use Composition?
• We can only use that when we can not modify
or extend the functionality of another class.
• It will not provide extra features.
• When one needs to use the class as it is
without any modification, the composition is
recommended.
Class Task
Create a class Book composed of pages.
Think class attributes and its behavior.