【问题标题】:Can not extend generic interface without compile errors无法在没有编译错误的情况下扩展通用接口
【发布时间】:2019-02-10 11:04:33
【问题描述】:

我有以下代码:

interface MVPView <A, B> {  
   void updateView(A a);  
   void attachPresenter(B presenter);  
}  

public class ConcreteMVPView implements MVPView<MyObject, MyPresenter> {  


}  

这编译得很好。

但如果我将代码更改如下:

interface MVP <B> {
   void attachPresenter(B presenter);
}

interface MVPView <A> extends MVP  {  
   void updateView(A a);  
}  

public class ConcreteMVPView implements MVPView<MyObject> {  
 // how can I implement that attachPresenter?  


}    

代码甚至无法编译。我做错了什么?

【问题讨论】:

  • "extends MVP" 使用的是原始类型。 MVP 需要一个类型变量。

标签: java oop generics inheritance android-mvp


【解决方案1】:

如果你只需要实现MVP,你可以这样做:

interface MVP<B> {
    void attachPresenter(B presenter);
}

public class MVPImpl implements MVPView<MyPresenter> {

}

如果你想实现MVPView,你可以这样做:

interface MVP<B> {
    void attachPresenter(B presenter);
}

interface MVPView<A, B> extends MVP<B> {
    void updateView(A a);
}

public class ConcreteMVPView implements MVPView<MyObject, MyPresenter> {

}   

【讨论】:

    【解决方案2】:

    我同意@Sun 的观点,如果您希望MVPMVPView 使用相同的泛型,那么让MVPView&lt;A&gt; implements MVP&lt;A&gt; 传递A。

    如果您希望 MVP 拥有自己的泛型,您需要 MVPView 拥有 2 个泛型类型。

    interface MVP<B>
    interface MVPView<A,B> extends MVP<B>
    class ConcreteMVPView implements MVPView<SomeClassA,SomeClassB>
    

    【讨论】:

      猜你喜欢
      • 2021-05-06
      • 2021-04-29
      • 2021-07-28
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 2014-05-25
      • 1970-01-01
      相关资源
      最近更新 更多