Java Composition Definition and Example

Java composition is a design correlation between two classes that is based on the “has-a” and “whole/part” associations, called an aggregation relationship. Composition takes the relationship one step further by ensuring that the containing object is responsible for the lifetime of the object it holds. If Object B is contained within Object A, then Object A is responsible for the creation and destruction of Object B.

Unlike aggregation, Object B cannot exist without Object A.

Composition Java Examples

Create a student class. This class holds information about individual students at a school. One piece of information stored is the student's date of birth. It's held in a GregorianCalendar object:

 import java.util.GregorianCalendar;
 
 public class Student {
 
   private String name;
   private GregorianCalendar dateOfBirth;
 
   public Student(String name, int day, int month, int year)
   {
     this.name = name;
     this.dateOfBirth = new GregorianCalendar(year, month, day);
   }
 
 //rest of Student class..
 
 } 

As the Student class is responsible for the creation of the GregorianCalendar object, it will also be responsible for its destruction (i.e., after the Student object no longer exists neither will the GregorianCalendar object). Therefore the relationship between the two classes is composition because Student has-a GregorianCalendar and it also controls its lifetime.

The GreogrianCalender object cannot exist without the Student object.

In JavaScript, composition is often confused with inheritance. However, the two are vastly different. Composition reflects a “has-a” relationship, while inheritance demonstrates an “is-a” relationship.  For example, in composition, a car has a wheel.

In inheritance, a sedan is a car.  Use composition to reuse code and composition with interfaces for polymorphism.

Format
mla apa chicago
Your Citation
Leahy, Paul. "Java Composition Definition and Example." ThoughtCo, Jan. 12, 2017, thoughtco.com/java-composition-definition-and-example-2034053. Leahy, Paul. (2017, January 12). Java Composition Definition and Example. Retrieved from https://www.thoughtco.com/java-composition-definition-and-example-2034053 Leahy, Paul. "Java Composition Definition and Example." ThoughtCo. https://www.thoughtco.com/java-composition-definition-and-example-2034053 (accessed November 19, 2017).