Wednesday, November 21, 2012

inheritance vs composition

About inheritance
In this article, I'll be talking about single inheritance through class extension, as in:

class Fruit {

    //...
}

class Apple extends Fruit {

    //...
}

In this simple example, class Apple is related to class Fruit by inheritance, because Apple extends Fruit. In this example, Fruit is the superclass and Apple is the subclass.



bout composition
By composition, I simply mean using instance variables that are references to other objects. For example:

class Fruit {

    //...
}

class Apple {

    private Fruit fruit = new Fruit();
    //...
}

In the example above, class Apple is related to class Fruit by composition, because Apple has an instance variable that holds a reference to a Fruit object. In this example, Apple is what I will call the front-end class and Fruit is what I will call the back-end class. In a composition relationship, the front-end class holds a reference in one of its instance variables to a back-end class.

The composition alternative
Given that the inheritance relationship makes it hard to change the interface of a superclass, it is worth looking at an alternative approach provided by composition. It turns out that when your goal is code reuse, composition provides an approach that yields easier-to-change cod


http://www.artima.com/designtechniques/compoinh.html

No comments:

Post a Comment