9

In my interface:

public <T> Result query(T query)

In my 1st subclass:

public <HashMap> Result query(HashMap queryMap)

In my 2nd subclass:

public <String> Result query(String queryStr)

1st subclass has no compilation warning at all while 2nd subclass has: The type parameter String is hiding the type String? I understand my parameter is hidden by the generics type. But I want to understand underneath what exactly happened?

1 Answer 1

17

It thinks you're trying to create a type parameter -- a variable -- whose name is String. I suspect your first subclass simply doesn't import java.util.HashMap.

In any event, if T is a type parameter of your interface -- which it probably should be -- then you shouldn't be including the <String> in the subclasses at all. It should just be

public interface Interface<T> {
  public Result query(T query);
}

public class Subclass implements Interface<String> {
  ...
  public Result query(String queryStr) { 
    ...
  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

As a style issue, I'd recommend against naming a type parameter String - or other commonly used Java class names. It will potentially confusing for anyone examining the code later on. If I see String in Java, I assume it's java.lang.String.
Oh, absolutely. I suspect that the example I give here is what the OP meant to do, though.
You may also want to take a look at this S&O question.
Yeah, I perhaps should have commented on the question instead of on your answer. :-)
What I am trying to achieve here is that, it's up to the subclass to decide whether they want to pass java.lang.String or java.util.HashMap as parameter to query() method. Interface just needs to say, subclasses have to implement query method, but I don't care about what type of parameter subclasses want to pass in. @oconnor0 Is your answer here best practice for this? or I should just use a wild card in the interface like query(?)
|

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.