Get rid of Unchecked overriding: return type requires unchecked conversion

3.9k Views Asked by At

Example code similar to my code.

public interface Builder<B, A> {
  B build(A a);
}

public class ClientBuilder implements Builder<String, Integer> {
  @Override
  public String build(Integer i) {
    return i.toString();
  }
}

public abstract class Client<B> {
  protected abstract <A> Builder<B, A> getBuilder();
}

public class ClientClient extends Client<String> {

  @Override
  protected Builder<String, Integer> getBuilder() {
    return null;
  }
}

In my ClientClient class I get a warning that says the following:

Unchecked overriding: return type requires unchecked conversion.Found 'Builder<java.lang.String,java.lang.Integer>', required 'Builder<java.lang.String,A>

Is there something I can do to get rid of this error?
I could use @SuppressWarnings("unchecked"), but that doesn't feel right.

In my example A is always an Integer but in my real code A can be one of two objects.

I guess I could also have two methods in my interface like this:

public interface Builder<B> {
  B build(Integer i);
  B build(String s);
}
1

There are 1 best solutions below

4
On

This isn't overriding the method correctly:

protected Builder<String, Integer> getBuilder() {
    return null;
}

You're missing the type variable.

Either declare it correctly:

protected <A> Builder<String, A> getBuilder() {
    return null;
}

or change the class declaration to allow you to provide the second type parameter:

public abstract class Client<B, A> {
  protected abstract Builder<B, A> getBuilder();
}