Friday, 7 May 2010

Composition / Inheritence

inheritance models the is-a relationship




class Fruit {

public String taste() {

System.out.println("It is sweet.");
return "Sweet";
}
}

class Orange extends Fruit {

//...
}




composition models the has-a relationship




class Fruit {

//...
}

class Orange {

private Fruit fruit = new Fruit();

public String taste() {
return fruit.taste();
}

}





* Composition allows you to delay the creation of back-end objects until (and unless) they are needed, as well as changing the back-end objects dynamically throughout the lifetime of the front-end object.

* With inheritance, you get the image of the superclass in your subclass object image as soon as the subclass is created, and it remains part of the subclass object throughout the lifetime of the subclass.

* It is easier to add new subclasses (inheritance) than it is to add new front-end classes (composition), because inheritance comes with polymorphism.

* The explicit method-invocation forwarding (or delegation) approach of composition will often have a performance cost as compared to inheritance's single invocation of an inherited superclass method implementation.

No comments:

Post a Comment