Aggregation (HAS-A) in Java

HAS-A RELATION
  1. Aggregation
  2. Composition
  • Aggregation represents part and whole relation between classes aggregation is a weaker relation in the way that in it either part or whole or both may have their independence existence.
  • e.g.:
    • Student has address.
    • Room has chairs.
    • Room has fans.
  • Composition repentance mode up of relation between  classes it is stronger relation in the way that in its existence of both participants depends on each other for
  • e.g.:
    • Room has walls.
    • Room has roof.
Example of Aggregation
Note: - Aggregation is implemented by containing object of a class as a data member in another class.
PermanentAddress.java
			           
public class PermanentAddress { public String city, state,country; public long pincode; PermanentAddress(String city, long pincode, String state, String country) { this.city=city; this.pincode=pincode; this.state=state; this.country=country; } }
StudentInfo.java
			           
public class StudentInfo { long enrolmentNo; String name; PermanentAddress perAddress; public StudentInfo(long enrolmentNo, String name, PermanentAddress perAddress) { this.enrolmentNo=enrolmentNo; this.name=name; this.perAddress=perAddress; } public void show() { System.out.println("Enrolment No : "+ enrolmentNo); System.out.println("Name : " + name); System.out.println("Address of Student======="); System.out.println("City : "+perAddress.city); System.out.println("Pincode :"+perAddress.pincode); System.out.println("State: "+perAddress.state); System.out.println("Country: "+perAddress.country); } public static void main(String s[]) { PermanentAddress address1 =new PermanentAddress( "Shakarpur",110092,"New Delhi", "India"); StudentInfo stdInfo =new StudentInfo(43600393,"Sunil" ,address1); stdInfo.show(); } }
Output

C:\JavaProgram\inheritance\Aggregation>javac PermanentAddress.java
C:\JavaProgram\inheritance\Aggregation>javac StudentInfo.java
C:\JavaProgram\inheritance\Aggregation>java StudentInfo
Enrolment No : 43600393
Name : Sunil
Address of Student=======
City : Shakarpur
Pincode :110092
State: New Delhi
Country: India
Download this example



 

Latest Tutorial


Most Visited Tutorial