Search code examples
javagenericstypesclone

Java: Reference "own type" in interface


I'd like to specify in an interface that an implementing method must return a class of its own type. For example, the clone method:

interface MyArray{
    MyArray clone();
}

interface MyVector extends MyArray{
    // ... 1d-array specific methods
    MyVector clone();
}

class MyDoubleVector implements MyVector{
    //...
    @Override
    public MyDoubleVector clone(){
        //...
        return new MyDoubleVector(Arrays.copyOf(data));
    }
}

Now I can call:

MyVector vec1 = new DoubleVector(...);
MyVector vec2 = vec1.clone();

I want to force all implementers of MyArray to have a clone method that returns the same type as the implementer. I could save a lot of lines if there were some built-in "meta-type" representing "same type as this class/interface" like:

interface MyArray{
    <ArrayOfSameType> clone();
}

And not have to redefine the method in extending interfaces in order call the vec1->vec2 clone operation as shown above.

Does Java have some built-in construct for doing this, or is copying and pasting a ton of boilerplate code just the sad fate of a java programmer?


Solution

  • You need to use generics to achieve this

    interface MyArray<A extends MyArray<A>> {
        A clone();
    }
    
    interface MyVector<A extends MyVector<A>> extends MyArray<A> {
    
    }
    
    class MyDoubleVector implements MyVector<MyDoubleVector> {
        //...
        @Override
        public MyDoubleVector clone(){
            //...
            return new MyDoubleVector(Arrays.copyOf(data));
        }
    }
    

    To clarify a point, you need the extends MyArray<A> to prevent a developer writing the following.

    MyArray<Integer> mi = new SomeMyArray<>();
    Integer i = mi.clone();
    

    This would compile just fine, but clearly should fail at runtime.