Joeblackdev
Joeblackdev

Reputation: 7327

Generic method - "unchecked conversion to conform to T from the type" warning

If I have the following:

public interface Foo {
   <T extends Foo> T getBlah();
}

public class Bar implements Foo {
   public Bar getBlah() {  
      return this;
   }
}

I get a warning in eclipse about the 'getBlah' implementation in class Bar:

- Type safety: The return type Bar for getBlah from the type Bar needs unchecked conversion to conform to T from the type 
 Foo

How can I fix this? And why am I getting the warning?

Thanks

Upvotes: 9

Views: 7047

Answers (3)

newacct
newacct

Reputation: 122449

<T extends Foo> T getBlah();

means that a caller can request any type as T to be returned. So no matter what class the object is, I can request some other random subclass of Foo of my choosing to be returned. The only value that such a method could validly return is null (unless it does unsafe casts), which is probably not what you want.

Upvotes: 4

Perception
Perception

Reputation: 80603

You are overriding a method from your interface, so your implementation you should match the signature from your specification:

public class Bar {
    @Override
    public <T extends Foo> T getBlah() {  
        return this;
    }
}

Now, if you were instead planning on creating a specifically parametized override of the entire implementation, then you need to specify the generic type as a part of the interface definition:

public interface Foo<T extends Foo<T>> {
    T getBlah();
}

public class Bar implements Foo<Bar> {
   @Override
   public Bar getBlah() {  
      return this;
   }
}

Upvotes: 15

Alessandro Santini
Alessandro Santini

Reputation: 2003

I am not sure what do you want to accomplish here but I think that returning Foo would be OK:

interface Foo {

  public Foo getBlah();

}

as you are not using the generic type anywhere in the parameters.

Upvotes: 3

Related Questions