Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between inheritance and composition?

As title says, the meaning of both eludes me.

like image 943
shubhendu mahajan Avatar asked Sep 21 '11 15:09

shubhendu mahajan


People also ask

What is the difference between inheritance and composition in C++?

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.

What is the difference between inheritance and composition in Python?

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.

Which is better inheritance or composition?

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.

What is difference between inheritance and aggregation?

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.


2 Answers

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 {
};
like image 50
pmr Avatar answered Nov 02 '22 23:11

pmr


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;
    }
}
like image 43
Brian Colvin Avatar answered Nov 02 '22 23:11

Brian Colvin