I was trying to use StringBuffer and Generics, but the code won't compile:
[Gen.java]
class Gen<T>
{
T ob;
//Constructor
Gen (T o)
{
ob = o;
}
void showtype()
{
System.out.println("Type of T is:"+ob.getClass().getName());
}
T getOb()
{
return ob;
}
}
[GenDemo.java]
public class GenDemo
{
public static void main(String[] args)
{
Gen<StringBuffer> objStr;
objStr = new Gen<StringBuffer> ("Hello"); //doesn't compile here.
objStr.showtype();
StringBuffer str = objStr.getOb();
}
}
I am a beginner. So, I apologize if this question is too basic for you. Can someone please help me? The code compiles well if I replace "StringBuffer" with "String"
Thanks
You're trying to initialise a Gen<StringBuffer>
with a String
. Change the initialisation to objStr = new Gen<StringBuffer>(new StringBuffer("Hello"))
and everything should be fine.