What is aggregation in Object-Oriented Programming?

What is aggregation in Object-Oriented Programming? Answer

In this lesson, you’ll get familiar with a new way of linking different classes.

We will cover the following:

  • Independent Lifetimes
  • Example

Aggregation follows the Has-A model that creates a parent-child relationship between two classes (where one class owns the object of another).

Independent lifetimes

  • In aggregation, the lifetime of the owned object does not depend on the lifetime of the owner.

If the owner object gets deleted, the owned object can continue in the program. In aggregation, the parent only contains a reference to the child, which removes the child’s dependency.

You can probably guess from the illustration above that we’ll need object references to implement aggregation.

Code

Let’s take the example of people and their country of origin. Each person is associated with a country, but the country can exist without that person:

class Country:
    def __init__(self, name=None, population=0):
        self.name = name
        self.population = population
        
    def printDetails(self):
        print("Country Name:", self.name)
        print("Country Population", self.population)
        
class Person:
    def __init__(self, name, country):
        self.name = name
        self.country = country
        
    def printDetails(self):
        print("Person Name:", self.name)
        self.country.printDetails()
        
c = Country("Wales", 1500)
p = Person("Joe", c)
p.printDetails()

# deletes the object p
del p
print("")
c.printDetails()

As we can see, the Country object (`c`) lives on even after we delete the Person object (`p`).This creates a weaker relationship between the two classes.

What is aggregation in Object-Oriented Programming? Review:

In our experience, we suggest you solve this What is aggregation in Object-Oriented Programming? and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the What is aggregation in Object-Oriented Programming?

Find on Educative

Conclusion:

I hope this What is aggregation in Object-Oriented Programming? would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.