2017-07-06 228 views
-2

嗨我在通用接口上有这个问题,如果有人能够以详细的方式解释我的答案不胜感激。通用接口扩展?

Inteface我

public interface I <T> { 
void f (T a); 
} 

接口Ĵ

public interface J <T extends I<T>>{ 
    void g(T b); 
} 

A类

public class A<T> implements J<T>{ 
    public void g(T b) { 

    } 
} 

A类中的代码会给出错误。 你能向我解释为什么它给出了一个错误?

A类FIX

public class A<T extends I<T>> implements J<T>{ 
    public void g(T b) { 

    } 
} 

可能有人向我解释为什么这个代码修正错误?

在此先感谢

回答

2

这是因为你的T不会扩展/实现I<T>

使用相同的通用占位符常常令人困惑。试着看它是这样的:

public interface I<TI> { 
    void f(TI a); 
} 

public interface J<TJ extends I<TJ>> { 
    void g(TJ b); 
} 

// Error:(17, 37) java: type argument TA is not within bounds of type-variable TJ 
// i.e. This `TA` does NOT implement/extend J<TA extends I<TA>> 
public class A<TA> implements J<TA> { 
    public void g(TA b) { 

    } 
} 

// Works fine because `TB extends I<TB>` 
public class B<TB extends I<TB>> implements J<TB> { 
    public void g(TB b) { 

    } 
} 
0

的原因是J <T extends I<T>>,所以当你实现这个接口,你需要为它提供一个扩展一类t,但你不能把它写这样A<T> implements J<T extends I<T>>。我猜想,这是不是你想要的,因为它创造了T级不必要的要求

所以,我会改变的是:

第一:J <T extends I<T>>变化J<T> extends I<T>。现在你有更简单的类型J.我认为这就是你需要/想要的。第二:你应该实现所有的方法,fi(T x)和f j(T x),所以就这么做。

这里是工作示例它是如何完成的。简单和工作。

public class MyClass { 

    public static void main(String[] args) throws Exception { 
     A a = new A<String>(); 
     a.fi("foo"); 
     a.fj("bar"); 
     return; 
    } 

    public interface I<T> { 
     void fi(T t); 
    } 

    public interface J<T> extends I<T> { 
     void fj(T t); 
    } 

    public static class A<T> implements J<T> { 
     // it is static only to be accessible from main() 
     public A() { 
      // default constructor 
     } 

     public void fi(T t) { 
      System.out.println("method from I, arg=" + b.toString()); 
     } 

     public void fj(T t) { 
      System.out.println("method from J, arg=" + b.toString()); 
     } 
    } 
} 

输出:

method from I, arg=foo 
method from J, arg=bar