Implementing multiple generic interfaces

后端 未结 2 1985
粉色の甜心
粉色の甜心 2021-01-19 01:07

I need to handle events of two different types but I\'m running into the following issue:

The interface EventListener cannot be implemented more than once with diffe

相关标签:
2条回答
  • 2021-01-19 01:38

    I'm trying to do the same thing in a project of mine, and there don't seem to be any elegant way to do it. The problem is that all the different versions of the generic interface methods have the same name and can have the same argument applied to them. At least if you are using subclasses, and as there is no guarantee that you won't, it won't compile. At least that's what I think is happening.

    class Fraction extends Number{
    ...
    }
    GenericInteface <T> {
    void method(T a);
    }
    
    NumberInterface extends GenericInteface <Number>{
    }
    FractionInterface extends GenericInteface <Fraction>{
    }
    ClassWithBoth implements NumberInterface, FractionInterface{
    void method(Number a){
    }
    void method(Fraction a){
    }}
    

    In this example, if something is calling ClassWithBoth's method named method with an argument that is a Fraction, it have to methods 2 chose from, both would work as a Fraction is also a Number. Doing something like this is stupid but there is no guarante that people don't, and in case they do java will have no idea what to do.

    The "Solution" I have come up with is to re-name the functions, like this.

    class Fraction extends Number{
    ...
    }
    GenericInteface <T> {
    void method(T a);
    }
    NumberInterface {
    void numberMethod(Number a);
    }
    FractionInterface {
    void fractionMethod(Fraction a);
    }
    ClassWithBoth implements NumberInterface, FractionInterface{
    void numberMethod(Number a){
    }
    void fractionMethod(Fraction a){
    }}
    

    Sadly that kinda eliminates the hole point of having the GenericInterface in the first place, as u can't really use it.

    0 讨论(0)
  • 2021-01-19 01:51

    There is only one handle(Object) method in reality. You are effectively write the same as

    public class CompositeListener implements EventListener {
        public void handle(Object event) {
            if (event instanceof PriceUpdate) {
                ///
            } else if (event instanceof OrderEvent) {
                ///
            }
        }
    }
    

    Without this checking logic, you can't effectively call your event listener in any case.

    0 讨论(0)
提交回复
热议问题