Inheritance, it is "IS A" relationship. Example, Employee is a person. Employee is base class and person is child class.
Composition is a "HAS A" relationship. Example Bike has a tyres. Bike class has reference of tyres class.
When you used inheritance and when you used composition.
Composition is a "HAS A" relationship. Example Bike has a tyres. Bike class has reference of tyres class.
When you used inheritance and when you used composition.
- The only way to get maximum advantage of both inheritance and composition in your designs is to ask yourself if you have a permanent is-a relationship. If yes then use inheritance. If not, use composition.
- For Example. An question to ask yourself when you think you have an is-a relationship is whether that is-a relationship will be constant throughout the lifetime of the application. For example, you might think that an Employee is-a Person, when really Employee represents a role that a Person. What if the person becomes unemployed? What if the person is both an Employee and a Supervisor? Such impermanent is-a relationships should usually be modelled with composition.
- And an Apple likely is-a Fruit, so I would be inclined to use inheritance. here no change to change is a relationship.
- As thinks for performance Inheritance is more costly compare to Composition. Every time you create object of child class before that parent constructor is called and memory is allocated for parent variable. Also you can not change behaviour of base class as run time.
- when you have need of the polymorphism then Polymorphism is achieved by inheritance.