Wednesday, January 17, 2018

Inheritance Vs Composition In Java

In Java we have two code reuse techniques

1.Inheritance
2.Composition

Inheritance is a technique to implement "Is-a" relationship in classes.

Composition is a technique to implement "Has-a" relationship in classes.Composition will be achieved by using instance variable of class that refers other objects of the class. ie Class A has an instance variable of Class B instance.

In Composition in java is that we can control the visibility of other object to client classes and reuse only what we need. Where in Inheritance all the details of other class will be available.If you dont need all the details of a class better use Composition.
Here is the Composition Example:

public class Details {

    private String Name;
    private int Age;

    public String getName() {
 return Name;
    }

    public void setName(String name) {
 Name = name;
    }

    public int getAge() {
 return Age;
    }

    public void setAge(int age) {
 Age = age;
    }
}


public class Person {

    //composition has-a relationship
    private Details detail;
   
    public Person(){
        this.detail=new Details();
        detail.setName("Rahul");
    }
    public long getAge {
        return detail.getName();
    }
}


public class TestPerson {

    public static void main(String[] args) {
 
        Person person = new Person();        
        String Name = person.getName();
    }

}

Here we are accessing only Name value of Details class.

No comments: