❮ Previous Next ❯

Aggregation

When the reference of a class act as a member in another class is known as Aggregation.

Aggregation represents HAS-A relationship. Consider a situation, Employee object contains many information such as id, name etc. It contains one more object named address, which contains its own information such as city, state, country etc.

It represent the concept of inheritance without no IS-A relationship. Inheritance should be used only if the relationship IS-A is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.

Let's see an example for better understanding this concept.


Address.java

package java8s;

public class Address {
      String city, state, country;
     
      Address(String city, String state, String country)
      {
            this.city=city;
            this.state=state;
            this.country=country;
      }

}

AgreegationExample.java

package java8s;

class Employee
{
      int id;
      String name;
      Address ad;
      Employee(int id, String name, Address ad)
      {
            this.id=id;
            this.name=name;
            this.ad=ad;
      }
     
      void show()
      {
            System.out.println(id+" "+name);
            System.out.println(ad.city+" "+ad.state+" "+ad.country);
      }
}
public class AgreegationExample {

      public static void main(String[] args) {
           
            Address ob1=new Address("BBSr","Odisha","india");
            Employee e=new Employee(101,"Trilochan",ob1);
            e.show();

      }

}

 

Output
aggregation
Note:

When we need to use property and behaviour of a class without modifying it inside our class then we use Aggregation as better, Whereas when we need to use and modify property and behaviour of a class inside our class, then we use Inheritance as better.


❮ Previous Next ❯


  Tutorials

Contact Us

address Plot No-N6/530,2ND Floor
Nayapalli,Jayadev Vihar
      Bhubaneswar-751015
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

2017 Silan Technology. All Rights Reserved