2

I have a class which is supposed to work by definition only with a String parameter.

So I thought about using

class MyClass<T extends String>

But then the compiler gives a warning that string is final and I can't extend it

Tried then with

class MyClass<String>

And got a warning because the parameter String is hiding class String.

What do I have to do?

4
  • 7
    Do you really need a generic type here? Commented May 20, 2012 at 22:03
  • Good question :) and now my problem is solved. I'll edit my post to explain Commented May 20, 2012 at 22:04
  • 1
    In your second example, you are creating a type parameter with the name String. You are not creating a type parameter which is limited to Strings. In fact, the type parameter in your second example could have any value. Commented May 20, 2012 at 22:05
  • What are you trying to do? Define a ctor or method that takes a string. Commented May 20, 2012 at 22:06

2 Answers 2

3

Thanks to the enlightening comment: "do you really need generics"?

I reviewed my code and found the problem. I wanted to use a type parameter because I'm implementing an interface with one

interface MyInterface<T>

and for some reason I thought I need the type paramter in the implementing class, like:

class MyClass<String> implements MyInterface<T>

But that doesn't make sense. What I needed to do is:

class MyClass implements MyInterface<String>

Solved :)

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

Comments

2

It seems to me that you don't need generics at all. You shouldn't overcomplicate your code if you don't need to. If your class is supposed to work only with String parameters, just omit the generic part.

So, instead of:

class MyClass<T extends String> {
  T myMethod() {
    //...
  }
  //...
}

Just do:

class MyClass {
  String myMethod() {
    //...
  }
  //...
}

Comments

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.