--Originally published at Alan TC201
One of cool thing you can do in Object-Oriented programming language is to reuse a code. There are two ways we can do code reuse, by implementation of inheritance or object composition. But you need to be careful how and what method you will use depending if it IS-A relationship or HAS-A relationship.
This image is very clear, but if you still can get the concept I will explain using the same example. You have a class with specifications about cars, like they uses some type of combustible, they move, and have doors, then you have a class name Maruti (a type of car) well that class is a relationship between the class car, everything inside the class car is valid for the class maruti.
On the other hand we have another class name engine, the maruti class HAS a relationship with the class engine because there are many types of engine but the maruti only cares about its engine, at the same time the engine has a relationship with the murati because that car needs an engine but the engine class does not care about the doors or of the car moves.
Down here are more specifications if you still are having trouble getting this.
- This refers to inheritance or implementation.
- Expressed using keyword “extends”.
- Main advantage is code reusability.
In object oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying “A is a B type of thing”. For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example House is a Building. But Building is not a House.
It is key point to note that you can easily identify the IS-A relationship. Wherever you see an extends keyword or implements keyword in a class declaration, then this class is said to have IS-A relationship.
Composition(HAS-A) simply mean use of instance variables that are references to other objects. For example: Maruti has Engine, or House has Bathroom.
- Has-A means an instance of one class “has a” reference to an instance of another class or another instance of same class.
- It is also known as “composition” or “aggregation”.
- There is no specific keyword to implement HAS-A relationship but mostly we are depended upon “new” keyword.
And a video that explains everything with details.