简体   繁体   中英

How to interface can extends 2 with that extends the same but with different generic parameters in java?

The problem:

base interface:

 IBase

descendants:

InterfaceA extends IBase<Interface1>

InterfaceB extends IBase<Interface2>

When I try:

InterfaceC extends InterfaceA, InterfaceB 

I receive compile error:

The interface IBase cannot be implemented more than once with different arguments

Does exist workaround? Thanks.

This is not possible and it cannot be in Java, at least. Think of the following scenario:

    interface Base<K> {
    K get();
}

interface A extends Base<String> {
    String get();
}

interface B extends Base<Integer> {
    Integer get();
}

interface AB extends A, B {
    ??
}

When you go try to implement AB, if it were possible, what type would the get() method return. In Java, two methods in a class cannot have the same name/args but different return types.... hence, this is forbidden.

If you actually need some functionality similar to what you would get should Java allow this, I would suggest the following:

    abstract class C {
    A a;
    B b;
    String aGet() {
        return a.get();
    }

    Integer bGet() {
        return b.get();
    }
}

Or, to keep generics:

abstract class C<K, T> {
    Base<K> a;
    Base<T> b;
    K getA() {
        return a.get();
    }

    T getB() {
        return b.get();
    }
}

Generics are basically compile time check only, so InterfaceA and InterfaceB are the same.

A general workaround for what you are suggesting is hard to come up with, you would probably have to specify your exact situation more. But do you really need THAT class to implement the two, why not two different classes? Maybe nested classes, or even anonymous inner class?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM