One Two Three
One Two Three

Reputation: 23497

generic in an interface in java

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();
    }
}

Upvotes: 1

Views: 70

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

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.

Upvotes: 0

Will
Will

Reputation: 14529

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;
    }
}

Upvotes: 4

Related Questions