Masterie ”has-a” and “is-a” .

One of the 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.

IS-A relationship

  • 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.

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.

HAS-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.

More info (http://learnwithharsha.com/my-first-java-lesson-is-a-and-has-a-relationships/)

And a video that explains everything with details.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s