Generic Class
A class that specify to any type is known as generic class. So to create the generic class of specific type. Now, we are using T type parameter.
By simple example we can create and use the generic class.
Creating a generic class:
[code lang=”java”] class MyGenrics<T>{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;}
}
[/code]
The T type designate that it can refer to any type for an example Integer, String etc. By specify the type for class, will be used to retrieve and store the data.
Using generic class:
To use the generic class let’s see the code.
[code lang=”java”]
class MyGenerics{
public static void main(String args[])
{
MyGen<Integer> g=new MyGen<Integer>();
mg.add(4);
System.out.println(g.get());
}}
[/code]
Output:4
[code lang=”java”]
public class MyGeneric<T> {
public static void main(String args[])
{
MyGeneric<Integer> g=new MyGeneric<Integer>();
g.add(4);
System.out.println(((Object) g.get()));
}
private Object get() {
return 4;
}
private void add(int i) {
}
}
[/code]