I have the following code in an abstract java class:
protected abstract <E extends HasText & IsWidget> E createNewDisplayWidget();
Which compiles fine. However if I call it anywhere, the compiler complains:
Bound mismatch: The generic method createNewDisplayWidget() of type DemoClass is not applicable for the arguments (). The inferred type HasText is not a valid substitute for the bounded parameter <E extends HasText & IsWidget>
Is there a way to require an abstract method to return something that should implement multiple interfaces?
Note: No, I cannot create a special interface that implements the two I like. GWT has widgets like Label which already implement said interfaces and I would like to use said widget.
Edit: I got the idea to do this from here (page 22):
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
I have given a try on the basis of your question and i was able to get through without an error. Please check the classes that i have created.
TestClass
public abstract class TestClass {
protected abstract <E extends HasText & IsWidget > E createNewDisplayWidget();
}
HasText class
public class HasText {
}
IsWidget
public interface IsWidget {
}
DemoClass
public class DemoClass extends HasText implements IsWidget{
}
TestClass1
public class TestClass1 extends TestClass{
@Override
protected DemoClass createNewDisplayWidget() {
// TODO Auto-generated method stub
DemoClass type = new DemoClass();
return type;
}
public void checkOut(){
if(createNewDisplayWidget() instanceof HasText || createNewDisplayWidget() instanceof IsWidget){
System.out.println("Yes it works");
}
else{
System.out.println("It doesnt");
}
}
public static void main(String[] args){
TestClass1 check = new TestClass1();
check.checkOut();
}
}
When i run my main program i always get "Yes it works". Please let me know am i missing something.
The problem was in Eclipse. I upgraded from 3.7 to 3.7.2 and the compiler error went away.
I don't know the details of what effect this had. If someone has a clue please feel free to update my answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With