Java Generic

Java Generic :

A parameterized type that operates by a class or an interface is called generic. It is introduced in java-5. It facilitate to write algo which is independent from any specific data type and type safety.

Through Generic its possible to create a single class or method that automatically works with all data types such as Integer, String Float, Double etc. It provide ability to reuse existing code safely and easily.

Note : Generic works only with Object type such as Integer, Float. It can’t work with primitive type.

Example :

You can better understand Generic through below code :


package com.pkjavacode.com;

/**
*
* @author pradeep
*/
public class GenericTest {

public static void main(String args[]) {

GenericExample<Integer> gt = new GenericExample(50);
int a = gt.getObject();
System.out.println(a);
GenericExample<String> gt2 = new GenericExample("Pradeep Yadav");
String b = gt2.getObject();
System.out.println(b);
}
}

class GenericExample<T> {

T obj;

public GenericExample(T obj2) {
obj = obj2;
}

public T getObject() {
return obj;
}
}

Output :

50
Pradeep Yadav

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