Generics-2

Hi Everyone! In my previous blog I gave you a brief insight of Generics. Today, we will go a little deeper into the topic.

So, the first question which might arise in everyone’s mind is why we need Generics. Let’s see the reasons-

Need of Generics

Some of the common reasons someone would use Generics would be-

  1. It helps to reuse the code.
  2. Helps in Code Maintenance.
  3. It makes us write lesser code.
  4. It improves the efficiency of the program.

 

Let’s say if a person wants to write an algorithm to add two numbers. And assuming that guy doesn’t know generics. He would write two separate¬†functions for adding two numbers. One would be using Integers (Whole Numbers) and the other one would be Floating point numbers (Decimals).

Something like this-

public int Add1 (int a, int b){

int c= a+b;

return c;

}

public float Add2(float a, float b){

float c=a+b;

return c;

}

 

So, the first function named “Add1” is to add two Integers (Whole Numbers) and the second function “Add2”, is to add two floating point numbers (Decimals).

Now, let’s see what would the person have written, had he known Generics

<T> Add(T a, T b){

T c=a+b;

}

 

He would have just written that, and it would have worked for both Integers and Floating Point Numbers. This reduces the number of lines of code drastically and hence improves the efficiency of the program.

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