Wednesday 22 October 2014

Java Composition Vs. Inheritance

What is Java Composition?

Java composition is a design technique using which we can reuse the java code.This is applicable when there is a has a relationship between two entity or classes.

eg. Student has an Address

Student.java
package com.nik.composition;
public class Student{

public void displayDetail(){
System.out.println("Student Detail is aaaa");
}
}


Address.java
package com.nik.composition;
public class Address{
Student stud; // Create Student instance variable as a data member of the Adderss class

public Address(){
stud=new Student();    //Initialize Student Object along with Address object
}
public void displayAddress()
{
System.out.println("Student Address is xxx");
}

public displayStudentCompleteDetail(){   // new method to access the Student method
stud.displayDetail();
 System.out.println("Student Address is xxx");
}
}

MainClass.java
public class MainClass{
public static void main(String[] arg) {
   Address addr=new Address();
   addr.displayStudentCompleteDetail(); // No need to create Student object
}
}

Advantage of using Java composition over Inheritance

1)Your code becomes loosely coupled and more flexible if you use composition.Changes in superclass  methods has no effect in their child classes overridden methods.
2)This approach more easily accommodates future requirements changes that would otherwise require a complete restructuring of business-domain classes in the inheritance model
3)Initial design is simplified by identifying system object behaviors in separate interfaces instead of creating a hierarchical relationship to distribute behaviors among business-domain classes via inheritance.


No comments:

Post a Comment