As title says, the meaning of both eludes me.
Composition is usually used for wrapping classes and to express relationships between classes that contain one another. Inheritance is used for polymorphism, where you have a base class and you want to extend or change its functionality.
Inheritance will extend the functionality with extra features allows overriding of methods, but in the case of Composition, we can only use that class we can not modify or extend the functionality of it. It will not provide extra features.
One more benefit of composition over inheritance is testing scope. Unit testing is easy in composition because we know what all methods we are using from another class. We can mock it up for testing whereas in inheritance we depend heavily on superclass and don't know what all methods of superclass will be used.
The difference is typically expressed as the difference between "is a" and "has a". Inheritance, the "is a" relationship, is summed up nicely in the Liskov Substitution Principle. Aggregation, the "has a" relationship, is just that - it shows that the aggregating object has one of the aggregated objects.
Inheritance expresses a is-a
relationship, while composition expresses a has-a
relationship between the two classes.
An example for composition is a polygon. It has a ordered sequence of Points. In C++ terms:
struct Polygon {
std::vector<Point> points;
};
While an logic_error
is a exception
:
struct logic_error : public exception {
};
Just google Inheritance vs Composition you'll get alot of results.
Using java as an example
public class Banana extends Fruit{ //<---Inheritance Banana is-a Fruit
private Peel bananaPeel; //<--Composition banana has a Peel
public Peel getPeel(){
return bananaPeel;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With