简体   繁体   English

使用不同类型参数实现接口的两个类

[英]Two classes implementing interface with different type arguments

class SingleTon{
   Data<A> a;
   Data<B> b;
   Data<C> c;
   // ... etc
   class Data<O extends I<O>>{
       O o;
       public void update(O o){
          this.o.update(o);
       }   
   }
}
interface I<T>{
   void update(T t);
}

class A implements I<A>{

    private String a;

    @Override
    public void update(A a) {
        this.a = a.a;
    }
}

class B extends A implements I<B>{

    private String b;

    @Override
    public void update(B b) {
       super.update(b);
       this.b = b.b;
    }
}
class C implements I<C> {public void update(C c){}}

This code cannot be compiled, because super and sub-classes trying to implements the same interface but with different type arguments.无法编译此代码,因为超类和子类试图实现相同的接口但具有不同的类型参数。

Interface I cannot be inherited with different type arguments (A,B), anyone has a workaround to solve this?接口 I 不能用不同的类型参数(A,B)继承,有人有解决方法吗?

No workaround are possible with such a hierarchy : in B you want to implement the i interface with two distinct generic types : A and B .对于这样的层次结构,不可能有解决方法:在B您希望使用两种不同的泛型类型实现i接口: AB
Generics are designed to bring more type safety and this possible ambiguity defeats that.泛型旨在带来更多的类型安全性,而这种可能的歧义使之失效。 From the client of the class, why update(B b) would be valid but update(A a) would be not ?从班级的客户看来,为什么update(B b)有效而update(A a)无效?
So the compiler will never accept it.所以编译器永远不会接受它。

But with composition you could do :但是通过组合你可以做到:

class B  implements i<B>{
    private A a;
    private String b;

    @Override
    public void update(B b) {
       super.update(b);
       this.b = b.b;
    }
}

And now you can use the A a field if needed from the B instance.现在,如果需要,您可以从B实例使用A a字段。

With the inheritance model given below, you'll achieve a contact of i through B in A .使用下面给出的继承模型,您将在A通过B实现i的联系。 You don't really need to implement i for class B<T> .你真的不需要为class B<T>实现i

See the example below:请参阅下面的示例:

interface i<T> {


}

class A<T> implements i<T> {

}

class B<T> extends A<T> {

}

Hope it helps you to understand the structure!希望对你理解结构有帮助!

I do not understand what is needed, but this code is compiled))我不明白需要什么,但此代码已编译))

interface i<T extends i<T>> {
    void update(T t);
}

class A<Q extends A<Q>> implements i<Q> {
    private String a;

    @Override
    public void update(A a) {
        this.a = a.a;
    }
}

class B<X extends B<X>> extends A<X> implements i<X>  {
    String b;

    @Override
    public void update(X b) {
        super.update(b);
        this.b = b.b;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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