1

Say I have this interface (which is NOT parameterised)

public interface MyInterface
{
     MyInterface copy();
}

How do I make sure any implementation of copy would return the actual subtype (and not MyInterface).

Eg.,

public Impl implements MyInterface
{
    @Override
    public Impl copy() <<<<< The returns type of this needs to be 'Impl'
    {
        return new Impl();
    }
}

But I can't prevent any implementation to do this:

public Foo implements MyInterface
{
    @Override
    public MyInterface copy() <<<<< The returns type of this needs to be 'Foo'
    {
        return new Impl();
    }
}
2
  • 1
    You don't need to worry about the reference of the return type. It's the actual object that will do everything as per polymorphism.
    – Braj
    Jun 5, 2014 at 20:06
  • In the calling code you can cast the return value from Foo.copy() to a Foo but you need to be sure then that you're calling copy on a Foo in the first place. Jun 5, 2014 at 20:10

2 Answers 2

4

You can specify a generic type which is a subclass of the interface:

interface MyInterface<T extends MyInterface<T>> {
    T copy();
}


class Foo implements MyInterface<Foo> {
    public Foo copy() {
        return null;
    }
}
2
  • I don't want to parameterize my MyInterface because it doesn't make any mean anything when put in the context. Jun 5, 2014 at 20:07
  • Don't ignore the warnings MyInterface is a raw type. References to generic type MyInterface<T> should be parameterized It's not generic inside T extends MyInterface
    – Braj
    Jun 5, 2014 at 20:08
0

Say I have this interface (which is NOT parameterised)

If you want to keep it non-parameterized, there is no solution that will satisfy both your examples. And I don't see why you would want to if you're programming to interfaces and don't control the implementations of your interface.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.