Combining type type parameters with interfaces in Java

As with many inheritance issues, it's hard for me to explain what I want to do. But a quick (but strange) 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 recognize that I want to use a specific Shell implementation for getTortoise() . Where am I wrong?

+4
source share
3 answers

Based on what you have indicated here, the problem is that:

 public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer 

Doesn't define ShellViewer (which is shared) correctly. It should be:

 public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer<T> 
+4
source

Do you want to:

 public class TortoiseShellViewer<T extends ToroiseShell> extends ShellViewer<T> 
+4
source

What is tShell in removeTortoise? Is this an instance of the Shell type that is in the ShellViewer base class?

0
source

Source: https://habr.com/ru/post/1341023/


All Articles