Extending your code
Extensibility of a class doesn't always depend on inheritance. Using composition and aggregation relationships between classes, we can create more cohesive and loosely coupled modules. Did I say no inheritance?
Let's first understand composition and aggregation in the real world. Let's say you are a student pursuing studies in a college in the Computer Science department. If you are wearing the Object Oriented Analysis and Design (OOAD) shoes you could easily understand the entities from the scenario. You guessed it! Student, College and Department.
A college has many departments and many students. The departments of the college can't exist without the college itself . This means “Departments” are owned by the college. Students can exist without the college, the ownership of students are not in the college alone. Students can look for a new college if the college doesn't exist. Can you identify a composition and aggregation relationship?
Composition is the idea of an object could be made up of, or composed of, other objects. The composed objects are intrinsic to the main object. Aggregation states that an object can bring together separate objects that has their own life time. The relation between body and heart is composition whereas car and wheel is aggregation.
Let's look at a more practical example in Java. An employee has an address and insurance. The insurance is optional for the employee but the employee should always have an address.
The lifetime of the address instance is intrinsic to the employee instance, but an insurance instance can exist on its own. If you see the code below in the Test class, once the employee instance is created, the address instance is also created within the employee class. The insurance instance is set explicitly and it is optional for an employee.
- public class Test {
-
- public static void main(String[] args) {
-
- Employee kannan = new Employee("kannan sudhakaran", "Andheri", "mumbai", "Maharashtra", "5055");
- System.out.println(kannan);
-
-
-
- InsuranceInfo insuranceInfo = new InsuranceInfo();
- insuranceInfo.setPolicyId("1001");
- insuranceInfo.setPolicyName("Life Insurance policy");
-
- kannan.setInsurance(insuranceInfo);
-
- System.out.println(kannan);
- }
-
- }
A quick sketch of the class diagram should look like this.
The following is the implementation in Java.