bing
Flat 10% & upto 50% off + Free additional Courses. Hurry up!

Aggregation and Composition (HAS-A)

Aggregation: It represents HAS-A relationship. Aggregation means a class have an entity reference. It is used because it provides code reusability. Inheritance is also used for code reusability but you should use inheritance when if the relationship IS-A is continued throughout the lifetime of the objects involved otherwise use aggregation.

e.g.

class CalculationOperation
{

public float square(float a)

{

return a*a;

}

public float cube(float a)

{

return a*a*a;

}

}

 

public class Calculator

{

CalculationOperation cop;  /* Class Calculator have an entity reference of class CalculationOperation */

public Calculator()

{

cop= new CalculationOperation();

}

public void getAns(float a)

{

System.out.println("Square is:"+cop.square(a));

System.out.println("Cube is:"+cop.cube(a));

}

public static void main(String[] arg)

{

Calculator calc=new Calculator ();

calc.getAns(2);

}

}

Output

Square is:4.0

Cube is:8.0

 

Composition: is also a HAS-A relationship in java classes. Java composition is archived by using instance variables that refers to other object.

e.g.

class Company

{

private String firstname;

public void setFirstname(String firstname)

{

this.firstname=firstname;

}

public void getFirstname()

{

System.out.println("Company name is: "+firstname);

}

}

public class CompanyDetails

{

Company cmp;

public CompanyDetails()

{

cmp=new Company();

cmp.setFirstname("Intellipaat");

}

public void getCmpName()

{

cmp.getFirstname();

}

public static void main(String[] arg)

{

CompanyDetails cd=new CompanyDetails();

cd.getCmpName();

}

}

Output

Company name is: Intellipaat

Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!

"0 Responses on Aggregation and Composition (HAS-A)"

Training in Cities

Bangalore, Hyderabad, Chennai, Delhi, Kolkata, UK, London, Chicago, San Francisco, Dallas, Washington, New York, Orlando, Boston

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

top

Sales Offer

  • To avail this offer, enroll before 07th December 2016.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer
offer-june

Sign Up or Login to view the Free Aggregation and Composition (HAS-A).