yitzih yitzih - 1 year ago 70
Java Question

Override method so that a parameter requires 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 {
<T extends MyAbstract> void someMethod(T param) {}

But I only want to allow a specific subclass of
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 Source

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> {
    public void someMethod(T param) {}


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