0

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

6
  • 3
    Why do you think it should compile? What surprises you about the error message? What do you think the type StringBuffer is? What's its relation with String? Commented Dec 24, 2015 at 22:56
  • 2
    Please don't use StringBuffer. It was replaced by StringBuilder more than ten years ago. Commented Dec 24, 2015 at 22:59
  • Can you post up there stack trace? Commented Dec 24, 2015 at 22:59
  • 3
    @KickButtowski if it doesn't compile, there won't be a stack trace (and it shouldn't compile) Commented Dec 24, 2015 at 23:02
  • 1
    @KickButtowski this doesn't compile, so you will get a compiler error, which doesn't include a stack trace. Commented Dec 26, 2015 at 14:19

2 Answers 2

3

You can't assign between incompatible types in Java. e.g. you can't do this

StringBuilder sb = "Hello"; // the object String is not a StringBuilder

What you can do is pass a reference of one type to the constructor of another e.g.

StringBuilder sb = new StringBuilder("Hello");

and you could do

Gen<String> str = new Gen<>("Hello");

or

Gen<StringBuilder> sb = new Gen<>(new StringBuilder("Hello"));

However, Java doesn't support implicit conversions of objects or references.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Perfect! Thanks sisyphus. Also, I am new to this forum...So I clicked up arrow to give you a vote, but it shows "-1"--I am not sure whether this is equivalent to "Dislike". I sincerely apologize if it is. I am not familiar with stackoverflow. This was my first post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.