Object Oriented
Programming – SCSJ2154
Class Relationships and
Aggregation
Associate Prof. Dr. Norazah Yusof
Aggregation
• Aggregation is a special form of association, which
represents an ownership relationship between two classes.
• Aggregation models the has-a relationship.
• The UML class diagram uses a hollow/empty diamond be
attached to the ends of association lines to indicate
aggregation.
2
Representing Aggregation in
Classes
An aggregation relationship is usually
represented as a data field in the aggregated
class.
3
The Student class
1 public class Student {
2 private String firstName, lastName;
3 private Address homeAddress, facultyAddress;
4 public Student(String first, String last, Address
5 home, Address college){
6 firstName=first;
7 lastName=last;
8 homeAddress=home;
9 facultyAddress=college;
10 }
4
The Student class
13 public String toString(){
14 String result;
15 result=firstName+" "+lastName+"\n";
16 result+= "Home
17 Address:\n\t"+homeAddress+"\n";
18 result+="Faculty’s
19 Address:\n\t"+facultyAddress;
20 return result;
}
}
5
The Address class
1 //Program 6.3
2 public class Address {
3 private String streetAddress, city, state;
4 private long zipCode;
5 public Address(String street, String town, String
6 st, long zip){
7 streetAddress=street;
8 city=town;
9 state=st;
10 zipCode=zip;
11 }
6
The Address class
12 public String toString(){
13 String result;
14 result=streetAddress+"\n\t";
15 result+=city +", "+state+" "+zipCode;
16 return result;
17 }
18 }
7
1 public class StudentTest{
2 public static void main(String[]a){
3 Address college= new Address("Faculty of Computer
4 Science and Information Systems, UTM", "Skudai", "Johor",
5 81310);
6 Address jHome=new Address("No. 4, Jalan Cenderasari,
7 Taman Mawar", "Muar", "Johor", 84000);
8 Student johan=new Student("Johan","Selamat",jHome,
9 college);
10 Address mHome=new Address("202 Jalan 5/6, Ampang
11 Ulu/Klang", "K. Lumpur", "Selangor", 56020);
12 Student munirah=new Student("Munirah", "Jamsari",
13 mHome, college);
14 System.out.println(johan);
15 System.out.println();
16 System.out.println(munirah);
17 }
18 }
8
Aggregation Example 1: FSKSM building has Lab,
LectureRoom and LecturerRoom
public class FSKSMBuilding
{ private Lab lab1;
private LectureRoom lect;
private LecturerRoom lectr;
}
Aggregation relationship is represented as a data field in the aggregated clas9s.