Search code examples
javagenericscovariancecontravariance

In Java, is it possible to use a generic interface with two type arguments as a base to subtype interfaces with one fixed type argument each?


I have a "base" interface:

public interface TargetActionDelegate<TTarget extends Target, TAction extends Action> {
    void handle(TTarget target, TAction action);
}

and the following related interfaces that fix one type argument:

public interface TargetDelegate<TTarget extends Target> {
    <TAction> void handle(TTarget target, TAction action);
}

public interface ActionDelegate<TAction extends Action> {
    <TTarget> void handle(TTarget target, TAction action);
}

Now it seems to me that these one-type-fixed interfaces should be supersets of the base interface, because they each handle the base case plus many others. Furthermore, since they both include the base case, they should be able to extend from the base case.

What I wanted to do was something like...

public interface TargetDelegate<TTarget extends Target> extends TargetActionDelegate<TTarget, ?ANYTHING? extends Action> {
    <TAction> void handle(TTarget target, TAction action);
}

public interface ActionDelegate<TAction extends Action> extends TargetActionDelegate<?ANYTHING? extends Target, TAction> {
    <TTarget> void handle(TTarget target, TAction action);
}

But I cannot find the right syntax for this OR (I think more likely at this point) I'm being really dopey about generics and Java generics in particular.

Guidance appreciated.


Solution

  • I believe what you want is simply :

    public interface ActionDelegate<TAction extends Action> extends TargetActionDelegate {
        <TTarget> void handle(TTarget target, TAction action);
    }
    

    and

    public interface TargetDelegate<TTarget extends Target> extends TargetActionDelegate {
        <TAction> void handle(TTarget target, TAction action);
    }