Generics

Generics is a concept which has become quite relevant in object oriented programming languages like C# and Java.The name itself,would give you an indication about the topic. It literally means “General”. It is about generalizing objects and methods.

A method  also known as a function, is basically an action which we would like the program to perform. And a method normally takes some arguments as input and returns a value. We define a data type for the input as well as the value which is returned by the function. The data types for most of the programming languages would consist of -Int, Boolean, Float, Byte, Char, Long.

The definition for a method would be something like this-

return type function_name(input type argument_name){}

 Example-

int add(int a, int b){

int c;

c=a+b;

return c;

}

This is a function which takes two values as input and adds them. And it returns the result as an Integer.

If Generics is used in this situation, it would appear something like this-

<T> add(int a, int b){

int c;

c=a+b;

return c;

}

 

If you would notice, we have  replaced int with T. “T” represents any data type and hence we are generalizing it.

Once, we are calling the method, we would write-

<int>add(24,56);

We specify the type only when we are calling the function or method.

One of the main advantages of implementing Generics in your program is it facilitates code reuse. This can be done because we are not explicitly specifying the data type for the arguments of the method.

 

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