What I did was just to find out how Generics works in Java. I wrote the following code:
public class Test { public static void main(String... args) throws Exception{ Foo o = new Foo<Integer>(new Integer(5)); o.fun(); } } class Foo<T> { private T t; public Foo(T t) throws InstantiationException, IllegalAccessException{ System.out.println("1. T is "+t.getClass()); this.t = (T)"test"; System.out.println("2. T is "+t.getClass()); } void fun(){ System.out.println("3. T is "+t.getClass()+" t = "+t); } }
And conclusion
1. T is class java.lang.Integer 2. T is Still class java.lang.Integer 3. T is class java.lang.String t = test
My question is: why does this change the class from Integer to String and does not show an error / exception.
And secondly, when I write t = 9; in function fun() , it shows:
incompatible types required: T found: java.lang.Integer
How do common classes work and how are they used?
Your answer will be very grateful!
java generics
Prashant shilimkar
source share