Relationship between classes

In java, we make different classes.

In this article, we will learn what kind of relationship may exist in classes.

Type of relationship between classes

relationship between classes in java

Inheritance:

in this, we inherited class to the user there member in other class by using extends keyword.

example :

class Animal 
{

   
}

class Dog extends Animal 
{
   
}

Here Dog class extends the class Animal. So, the relationship between this class is  IS-A relationship:

Dog IS A Animal.

It is a tightly coupled relationship which means if we change in a one-class it will affect both classes


Association:

Association is the most commonly used relationship in java. It defines the HAS-A Relationship between the class and its members.

For example

class Animal 
{
    String Name;

   
}

Animal HAS-A Name

Another example:

class Car 
{

   
}

class Engine //notice here we not use extends keyword
{
    Car cp = new Car();
   
}

 Here is also relationship build

Car HAS-A Engine

It is a non-blood or  not tightly coupled relationship which means if we change in a one-class it will do not affect both classes


Aggregation and composition:

These two are the type of association.

Let’s understand aggregation and composition with examples. Suppose we have 3 class

Aggregation and composition in java

Aggregation:

If the professor does not exist it will not affect the collage

If collage not exist it will not affect the professor

So, here the relationship is a week. this type of relation called aggregation in java

Composition:

If the branch does not exist it will  affect the collage

If collage not exist it will  affect the branch

So, here the relationship is strong. this type of relation called aggregation in java



SHARE THIS PAGE





Important Link