yitzih yitzih - 3 months ago 10
Java Question

Override method so that a parameter allows for a subclass

I have an abstract super class and 2 classes that extend it

public abstract class MyAbstract {}

public class A extends MyAbstract {}

public class B extends MyAbstract {}


I have an interface which has a method that takes a subclass of MyAbstract as its parameter

public interface MyInterface {
<T extends MyAbstract> void someMethod(T param);
}


I then have a class that implements that interface

public class AnotherClass implements MyInterface {
@Override
<T extends MyAbstract> void someMethod(T param) {}
}


But I only want to allow a specific subclass of
MyAbstract
to be used in the method.

Here are a couple of the things I tried so far:

<T extends A> void someMethod(T param); //doesn't override the method

void someMethod(A param); //doesn't override the method


Is there anyway to have a interface take a generic parameter and the implementer of that interface specify a more restricted version of that parameter or is this simply not possible?

Answer

Yes, you make the interface itself actually take the generic parameter:

public interface MyInterface<T extends MyAbstract> {
    void someMethod(T param);
}

Then you can limit it where used:

public class AnotherClass<T extends A> implements MyInterface<T> {
    @Override
    public void someMethod(T param) {}
}

Or:

public class AnotherClass implements MyInterface<A> {
    @Override
    public void someMethod(A param) {}
}
Comments