New to inheritance and generics so bear with me if my question is stupid:
I have the following:
public abstract class car {
private long id;
private String name;
public car (long id, String name) {
this.id = id;
this.name = name;
}
public final long getID(){
return id;
}
public final String getName(){
return name;
}
}
public class sedan extends car {
public sedan(long id, String name) {
super (id, name);
}
...
}
public class jeep extends car {
public jeep(long id, String name) {
super (id, name);
}
...
}
I'm trying to extend the ArrayAdapter for a spinner as follows:
public class DropdownAdapter extends ArrayAdapter<car> {
private Context context;
private List<car> values;
public DropdownAdapter(Context context, int textViewResourceId, List<car> values) {
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
...
}
The problem comes when I try to use it:
adapter = new DropdownAdapter (this, android.R.layout.simple_spinner_item, lstSedan);
will give me the error: The constructor DropdownAdapter (ScreenItemList, int, List< sedan >) is undefined
adapter = new DropdownAdapter (this, android.R.layout.simple_spinner_item, lstJeep);
will give me the error: The constructor DropdownAdapter (ScreenItemList, int, List< jeep >) is undefined
What is the issue here? Why can't I use lstSedan or lstJeep as parameters when they are derived from car? How do I resolve this? Thanks!
You defined a method that expects a parameter of type List<a>
public SpinnerAdapter(Context context, int textViewResourceId, List<a> values)
That is, it expects a list of items of type a
.
But then you pass a parameter of type b
that inherited a
, instead of a parameter of type List<b>
Try to use this way:
List<b> lstB= new ArrayList<b>();
adapter = new SpinnerAdapter (this, android.R.layout.simple_spinner_item, lstB);
As JoxTraex said, you should read java name convention
Update:
Sorry, I made a mistake. Because java doesn't allow passing List<ChildClass>
parameter to List<ParentClass>
, so you shouldn't use inheritance in this case. Try using generic
public class DropdownAdapter extends ArrayAdapter<T> {
private Context context;
private List<T> values;
public DropdownAdapter(Context context, int textViewResourceId, List<T> values) {
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
...
}
And this function call should work:
adapter = new SpinnerAdapter (this, android.R.layout.simple_spinner_item, lstB);