Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining generic type parameters with interfaces in Java

As with many inheritance problems, I find it hard to explain what I want to do. But a quick (but peculiar) example should do the trick:

public interface Shell{


    public double getSize();

}

public class TortoiseShell implements Shell{
     ...
     public double getSize(){...} //implementing interface method
     ...
     public Tortoise getTortoise(){...} //new method
     ...
}

public class ShellViewer<S extends Shell>{

     S shell;

     public ShellViewer(S shell){
         this.shell = shell;
         ...
     }

}

public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer{

    public TortoiseShellViewer(T tShell){
         super(tShell); //no problems here...
    }

    private void removeTortoise(){
        Tortoise t = tShell.getTortoise(); //ERROR: compiler can not find method in "Shell"
        ...
    }
}

The compiler does not recognise that I want to use a specific implementation of Shell for getTortoise(). Where have I gone wrong?

like image 918
MattLBeck Avatar asked Feb 26 '23 00:02

MattLBeck


1 Answers

Based on what you've given here, the problem is that:

public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer

does not specify ShellViewer (which is generic) correctly. It should be:

public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer<T>
like image 186
ColinD Avatar answered Feb 27 '23 13:02

ColinD