Reputation: 32269
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?
Upvotes: 2
Views: 134
Reputation: 1952
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() {
//...
}
//...
}
Upvotes: 2
Reputation: 32269
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 :)
Upvotes: 3