Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Polymorphic Return Type in an Abstract Method?

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

like image 830
McTrafik Avatar asked May 09 '12 22:05

McTrafik


2 Answers

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.

like image 114
raddykrish Avatar answered Oct 28 '22 15:10

raddykrish


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.

like image 35
McTrafik Avatar answered Oct 28 '22 17:10

McTrafik