Search code examples
javagenericsoverridingabstract-classtype-bounds

Inheritance of generic typed method from abstract class -- convert to specific type


(Working in Java) I have an abstract class with generic typing throughout the whole class:

public abstract class ConnectionProcessor<T>
{
    public void process()
    {
        for (List<T> resultsPage : connection)
        {
            processPage(resultsPage);
        }
    }

    protected abstract void processPage(List<T> resultsPage);
}

I have another class that extends said abstract class, with the following declaration:

public class AlbumProcessor<Album> extends ConnectionProcessor
{
    @Override
    protected void processPage(List resultsPage)
    {
        //Do stuff here specific to Album
    }
}

This declaration works fine, but in processPage I want to do Album-specific things, and I try to avoid casting when I don't need to use it. I would PREFER this to be the method declaration:

protected void processPage(List<Album> resultsPage)

But this doesn't meet the requirements for overriding processPage from ConnectionProcessor. Why is this? How can I get the desired behavior? I would think that in AlbumProcessor I could just plug in <Album> everywhere ConnectionProcessor has <T>, but that just isn't the case.


Solution

  • Try

    //extend prameterized version of ConnectionProcessor<T> with Album as actual type argument
    public class AlbumProcessor extends ConnectionProcessor<Album> {
    

    instead of

    public class AlbumProcessor<Album> extends ConnectionProcessor {
    

    When you do the above you are exteding the raw version of the generic type ConnectionProcessor<T> and introducing a new formal type parameter - Album (like T) which is not an actual type argument in that case.