简体   繁体   中英

Calling constructor of extended class

I have this class :

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);
    }

the next class extends the previous class and this is its constructor:

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

(MyEntity class implements IFilterableEntity <String>)

problem is that I got error

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

How can I call the constructor of BaseFilterableArrayAdapter from MyAdapter ?

Generics are invariant so List<MyEntity> is not the same type as List<IFilterableEntity<T> . You could make the super class itself generic and make the sub class contain a <MyEntity<T> generic type argument

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

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

It's a known Java pain-in-the-ass. Look at the following code:

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>();
    }
}

It won't compile:

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)

Unfortunatelly you have to convert it manually before passing to superconstructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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