Generic Programming
Generic Programming
class MyGen<T>{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;}
}
The T type indicates that it can refer to any type (like String, Integer,
Employee etc.). The type you specify for the class, will be used to
store and retrieve the data.
Generic class
Let’s see the code to use the generic class.
class TestGenerics3{
public static void main(String args[]){
MyGen<Integer> m=new MyGen<Integer>();
m.add(2);
//m.add("vivek");//Compile time error
System.out.println(m.get());
}}
Output:2
Generic Method
Like generic class, we can create generic method that can
accept any type of argument.