4

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?

4
  • 1
    Mostly you've gone wrong by assuming that Java generics are the same as C++'s templates. Commented Feb 23, 2011 at 18:55
  • Might want to remove the huge red herring of getTortoise returning a double in one place and a Tortoise elsewhere. Commented Feb 23, 2011 at 19:04
  • 1
    Woops. Thanks! Edited for future reference Commented Feb 23, 2011 at 19:08
  • Another thing that'd be helpful would be to include all relevant information in the code you're showing... the declaration of the field tShell in ShellViewer is important here but missing. Commented Feb 23, 2011 at 19:10

3 Answers 3

4

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you. My understanding in generics just increased 10-fold.
4

You want this:

public class TortoiseShellViewer<T extends ToroiseShell> extends ShellViewer<T>

Comments

0

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

1 Comment

It should be an instance of TortoiseShell. Or, an instance of generic type T, which extends TotoiseShell. Sorry if it's a bit confsuing to read. My actual code was too bogged down in its own application to use here...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.