0

I have an interface HTTPSequence. I also have an abstract class AbstractHTTPFactory which in turn has an abstract method returning ArrayList<HTTPSequence>. In classes derived from AbstractHTTPFactory I want to override those methods to return ArrayList<[Class implementing HTTPSequence]>.

Is it possible ? Now compiler gives my an error suggesting that I change overriden methods signature to HTTPSequence.

// abstract class with abstract method returning ArrayList of objects implementing interface
abstract public class AbstractHTTPFactory {
    abstract ArrayList<HTTPSequence> make();
}
// Specific class that returns ArrayList of objects of the class implementing HTTPSequence
public class RecipesHTTPFactory extends AbstractHTTPFactory{
    public ArrayList<Recipe> make() {
    }
}
// interface
public interface HTTPSequence {
}
// one of the classes implementing the above interface
public class Recipe implements HTTPSequence {
}

And the message Eclipse gives me is:

Multiple markers at this line - The return type is incompatible with AbstractHTTPFactory.make() - implements ....ider.AbstractHTTPFactory.make

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181

2 Answers2

6

You could write your AbstractClass method to return ArrayList<? extends Interface>, and then you do not have to change the derived class method signatures

Attila
  • 28,265
  • 3
  • 46
  • 55
0

The following design would allow you to avoid having to return a wildcarded generic type, which are of limited use to the caller:

abstract public class AbstractHTTPFactory<T extends HTTPSequence> {
    abstract ArrayList<T> make();
}

public class RecipesHTTPFactory extends AbstractHTTPFactory<Recipe> {
    public ArrayList<Recipe> make() { ... }
}

Now you can call new RecipesHTTPFactory().make() and get back an ArrayList<Recipe> instead of an ArrayList<? extends HTTPSequence>.

Also note that unless the caller specifically expects an ArrayList, it is better for make() to return a List<T>.

Community
  • 1
  • 1
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181