【问题标题】:How to interface can extends 2 with that extends the same but with different generic parameters in java?java - 如何接口可以扩展2与扩展相同但在java中具有不同的泛型参数?
【发布时间】:2012-05-04 10:18:54
【问题描述】:

问题:

基础接口:

 IBase

后代:

InterfaceA extends IBase<Interface1>

InterfaceB extends IBase<Interface2>

当我尝试时:

InterfaceC extends InterfaceA, InterfaceB 

我收到编译错误:

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

是否存在解决方法? 谢谢。

【问题讨论】:

  • 我已经检查过了 - 但解决方案是类的集群,我不知道如何为接口制作它。

标签: java interface multiple-inheritance


【解决方案1】:

这是不可能的,至少在 Java 中是不可能的。 考虑以下场景:

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

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

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

interface AB extends A, B {
    ??
}

当你去尝试实现 AB 时,如果可能的话,get() 方法会返回什么类型。在 Java 中,一个类中的两个方法不能具有相同的名称/参数但返回类型不同......因此,这是被禁止的。

如果您确实需要一些类似于 Java 允许的功能,我建议如下:

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

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

或者,保留泛型:

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

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

【讨论】:

    【解决方案2】:

    泛型基本上只是编译时检查,所以 InterfaceA 和 InterfaceB 是一样的。

    很难想出针对您所建议的一般解决方法,您可能需要详细说明您的具体情况。但是你真的需要那个类来实现这两个,为什么不是两个不同的类呢?也许是嵌套类,甚至是匿名内部类?

    【讨论】:

    • 是的,我真的需要那个类应该用作 InterfaceA 和/或 InterfaceB
    • 您可以在不指定泛型类型的情况下执行此操作,并使用 Object 实现一次,然后使用老式的方式执行强制转换(并忽略警告)
    • 尝试通过实现 IBase 来做到这一点,然后呢?
    猜你喜欢
    • 2012-10-17
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    相关资源
    最近更新 更多