In this section, we will create a class with generic type T. Classes will consist of the variable of type T and will also have a general purpose method that will return the variable of type T:
public class MyGeneric<T> { T input; public MyGeneric(T input) { this.input=input; } public T getInput() { return input; } }
As described previously, MyGeneric is the class. It consists of the variable input of type T, a constructor to construct the object of the MyGenric class and initialize the variable input and a method that returns the value of T.
Now, let's implement it:
public class MyGenericsDemo { public static void main(String[] args) { MyGeneric<Integer> m1 =new MyGeneric<Integer>(1); System.out.println(m1.getInput()); //It will print '1' MyGeneric<String> m2 =new MyGeneric<String>("hello"); System.out.println(m2.getInput()); //It will print 'hello' } }
Here, we have created two objects of the MyGeneric class, one with an integer type and the other with a string type. When we invoke the getInput method on both objects, they will return the value of their respective type.