【问题标题】:Calling constructor of extended class调用扩展类的构造函数
【发布时间】:2014-05-29 20:03:22
【问题描述】:

我有这门课:

public class BaseFilterableArrayAdapter<T> extends ArrayAdapter< IFilterableEntity<T> > implements SectionIndexer 
{


    public BaseFilterableArrayAdapter(Activity context,int id_row_template,  List<IFilterableEntity<T>> data)
    {
        super(context, id_row_template, data);
    }

下一个类扩展了前一个类,这是它的构造函数:

public MyAdapter(Activity context, List<MyEntity> data) 
    {
        super(context, R.layout.listview_row, data);    
        ....
    }

(MyEntity 类实现 IFilterableEntity

问题是我出错了

The constructor `BaseFilterableArrayAdapter<String>(Activity, int, List<MyEntity>)` is undefined

如何从MyAdapter调用BaseFilterableArrayAdapter的构造函数?

【问题讨论】:

  • 注意第三个参数List&lt;IFilterableEntity&lt;T&gt;&gt;vs List&lt;MyEntity&gt;这两个IFilterableEntity&lt;T&gt;MyEntity有什么联系吗?
  • 您还应该发布您声明课程的方式。错误表明它需要一个模板类。
  • 您需要先将您的List&lt;MyEntity&gt; 重组为List&lt;IFilterableEntity&lt;T&gt;&gt;
  • 将您的扩展更改为 MyAdapter extends BaseFilterableArrayAdapteryMyEntity> 然后它应该可以工作

标签: java android interface android-activity adapter


【解决方案1】:

泛型是不变的,所以List&lt;MyEntity&gt;List&lt;IFilterableEntity&lt;T&gt; 的类型不同。您可以使超类本身泛型,并使子类包含&lt;MyEntity&lt;T&gt; 泛型类型参数

public class BaseFilterableArrayAdapter<T> extends ArrayAdapter<T> 
                                                     implements SectionIndexer{

    public BaseFilterableArrayAdapter(Activity context, int idRowTemplate, List<T> data) {
        super(context, idRowTemplate, data);
        ...         
    }
}

【讨论】:

  • 感谢您的回答,我在帖子中为 BaseFilterableArrayAdapter 类添加了一些代码。现在的问题是,它说:The constructor ArrayAdapter&lt;IFilterableEntity&lt;T&gt;&gt;(Activity, int, List&lt;capture#1-of ? extends IFilterableEntity&lt;?&gt;&gt;) is undefined
  • 由于 ArrayAdapter 使用泛型类型参数,您不能将它们与通配符混合。您可以更改泛型类型参数以允许派生类 (MyAdapter) 参数匹配,如图所示
【解决方案2】:

这是一个众所周知的 Java 痛点。看下面的代码:

import java.awt.List;
import java.util.ArrayList;

class Animal {

}

class Cat extends Animal {

}

public class TemplatedList {
    public static void main(String[] args) {
        ArrayList<Animal> animals = new ArrayList<Cat>();
    }
}

它不会编译:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Type mismatch: cannot convert from ArrayList<Cat> to ArrayList<Animal>

    at TemplatedList.main(TemplatedList.java:14)

不幸的是,您必须在传递给超级构造函数之前手动转换它。

【讨论】:

猜你喜欢
  • 2014-04-18
  • 2018-09-26
  • 2013-11-15
  • 1970-01-01
  • 2021-02-13
  • 2013-05-29
  • 2019-01-07
  • 2016-08-26
  • 1970-01-01
相关资源
最近更新 更多