Has a Relationship - rahul00773/JavaConcepts GitHub Wiki

Has a Relationship is also known as Composition or Aggregation.

There is no specific keyword to implement has a relationship but most of the times we are depending on new keyword

The main advantage of has a relationship is the reusability of the code.

class Car {

Engine e = new Engine(); // Car has a engine reference }

class Engine{

// Engine specific method

}

Difference between composition and Aggregation:

Composition:

Without existing container objects if there is a chance of existing contained objects then container and contained objects are strongly associated and this strong association is nothing but composition.

Ex: University consists of Several departments without existing universities there is no chance of existing departments. Hence the university and department are strongly associated. And this strong association is nothing but composition.

Aggregation:

Without existing container objects if there is a chance of existing contained object then container and contained objects are weekly Associated and this week association is nothing but aggregation.

Ex: Department consists of several professors without existing departments there may be a change of existing professor objects. Hence department and professor objects are weekly associated. And this week association is nothing but an aggregation

Note:

In composition, Objects are Strongly associated whereas in aggregation Objects are Weekly associated. In composition container object holds directly contained objects. Whereas in aggregation container objects hold just references of contained objects.

Is A Vs Has A:

If we want total functionality of a class then automatically we should go for is a relationship.

Ex: Person class functionality complete functionality required for student class

If we want part of the functionality then we should go for has a relationship

Ex. Test Class contains 100 methods and demo method required only one-two methods