0

So I was hoping to be clever by creating an abstract class called SearchableModel which looks like this:

public abstract class SearchableModel {

    public abstract String getId();

    public abstract String getName();
}

And then creating one RecyclerViewAdapter that would work for any class extending this abstract one. My concrete class looks like this:

public class School extends SearchableModel{

    @SerializedName("external_school_id")
    private String id;

    @SerializedName("name")
    private String name;

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getName() {
        return id;
    }
}

And the RecyclerViewAdapter is like this:

public class SearchableItemAdapter extends RecyclerView.Adapter<SearchableItemAdapter.ViewHolder> {

    private List<SearchableModel> items;

    public SearchableItemAdapter(List<SearchableModel> items) {
        this.items = items;
    }

    @Override
    public SearchableItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(SearchableItemAdapter.ViewHolder holder, int position) {
        SearchableModel item = items.get(position);
        holder.nameText.setText(item.getName());
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{

        @BindView(R.id.text_list_name)
        TextView nameText;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}

My thought was that I would simply be able to define a List<School> schools and then apply it to the adapter in the constructor using new SearchableItemAdapter(schools). However when I try this I get the following error:

Incompatible Types. Required List<SearchableModel>. Found List<School>

My understanding is since School extends SearchableModel it should be able to be used in place of it. Am I completely off base in the way inheritance works in Java or is there something else going on here?

drawinfinity
  • 315
  • 4
  • 21

1 Answers1

3

You should use List<? extends SearchableModel> items instead.

You've misunderstood a bit of how it works, this post explains it extremely well:
https://stackoverflow.com/a/3009779/2877453

Moonbloom
  • 7,738
  • 3
  • 26
  • 38