2

I have the following abstract class:

public abstract class AbstractSharpCollection<T> implements SharpCollection<T>

and an interface

public interface SharpCollection<T> extends Iterable<T>
{
    SharpCollection<T> tail();
}

There's a lot of other methods defined in SharpCollection, which return another SharpCollection. The logic of all those methods rely only on the iterator.

I want to be able to create a method on AbstractSharpCollection, such that the call to tail() would return the instance of the subclass, and not the superclass.

Something like

public <V extends SharpCollection<T>> V tail() { //code logic here }

I know that I can override the return type on the subclasses that extend the AbstractSharpCollection, but having to override all the methods only to change the return type is really ugly, troublesome, and prone to errors.

Is there any way at all that I can achieve what I want?

Thanks for the help.

Vinicius Seufitele
  • 885
  • 1
  • 6
  • 15

1 Answers1

2

Implementing tail would be quite difficult. null is the only valid return value.

It appears you need to parameterise the SharpCollection so that it "knows" the actual interface type being used:

public interface SharpCollection<
    THIS extends SharpCollection<THIS, T>,
    T
> extends Iterable<T> {
    THIS tail();
}

Unfortunately this complicates the client code as well.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • hi, can you please ellaborate on your solution, din't quiet get it. or provide a help link to it. :) thanks. –  Aug 16 '12 at 15:28
  • Actually, I'm using this solution to solve the tail problem, but it doesn't solve all the cases, and subclasses have to declare two parameter types, when it should be only one. – Vinicius Seufitele Aug 16 '12 at 15:31
  • @Aman See my answer here for more details on implementing this pattern: http://stackoverflow.com/a/7355094/697449 – Paul Bellora Aug 16 '12 at 17:30