Java Reference
In-Depth Information
Sometimes an object of a class contains an object of another class, which indicates a whole-part relationship.
This relationship is called aggregation. It is also known as has-a relationship. The example of has-a relationship is
“A person has an address.” As a whole-part relationship, the person represents the whole and the address represents
the part. Java does not have any special feature that lets you indicate a has-a relationship in your code. In Java code,
aggregation is implemented by using an instance variable in the whole, which is of the type part. In this example, the
Person class will have an instance variable of type Address , as shown below. Note that an object of the Address c lass
is created outside of a Person class and passed in to the Person class constructor.
public class Address {
// Code goes here
}
public class Person {
// Person has-a Address
private Address addr;
public Person(Address addr) {
this.addr = addr;
}
// Other code goes here
}
Composition is a special case of aggregation in which the whole controls the life cycle of the part. It is also known
as part-of relationship. Sometimes, has-a and part-of relationships are used interchangeably. The main difference
between aggregation and composition is that in composition the whole controls the creation/destruction of the
part. In composition, the part cannot exist by itself. Rather, the part is created and destroyed as a part of the whole.
Consider the relationship “A CPU is part-of a computer.” You can also rephrase the relationship as “A computer has a
CPU.” Does the existence of a CPU outside a computer make sense? The answer is no. It is true that a computer and
a CPU represent a whole-part relationship. However, there are some more constraints to this whole-part relationship
and that is, “The existence of a CPU makes sense only inside a computer.” You can implement composition in Java
code by declaring an instance variable of a type part and creating the part object as part of creation of the whole as
shown below. A CPU is created when a Computer is created. The CPU is destroyed when the computer is destroyed.
public class CPU {
// Code goes here
}
public class Computer {
// CPU part-of Computer
private CPU cpu = new CPU();
// Other code goes here
}
Java has a special class type called inner class, which can also be used to represent composition. An object of an
inner class can exist only within an object of its enclosing class. The enclosing class would be the whole and the inner
class would be the part. You can represent the part-of relationship between CPU and computer using an inner class,
as follows:
Search WWH ::




Custom Search