调用扩展类的构造函数

时间:2014-04-15 12:47:59

标签: java android interface android-activity adapter

我有这堂课:

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&lt; String&gt;)

问题是我收到了错误

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

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

2 个答案:

答案 0 :(得分:1)

泛型不变,因此List<MyEntity>List<IFilterableEntity<T>的类型不同。您可以使超类本身具有通用性,并使子类包含<MyEntity<T>泛型类型参数

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

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

答案 1 :(得分:0)

这是一个众所周知的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)

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