Java compile error with generics

public class IRock
    public List<IMineral> getMinerals();

public class IMineral { ... }

public class SedimentaryMineral implements IMineral { ... }

public class SedimentaryRock implements IRock
    private List<SedimentaryMineral> minerals;

    public List<SedimentaryMineral> getMinerals()
        return minerals;

Getting a compiler error:

Type mismatch: cannot convert from List<SedimentaryMineral> to List<IMineral>.

I understand that I can't convert an impl back to its API interface (because an API is just than - an API). But I'm confused as to why I'm getting a compiler error! Shouldn't Java honor the fact that SedimentaryMineral is an impl of IMineral and allow this?!?

Along with an explanation as to why I'm getting this compiler error, perhaps someone could point out why my approach here is "bad design" and what I should do to correct it. Thanks in advance!


Imagine if this compiled:

List<SedementaryMineral> list = new ArrayList<>();
list.put(new SedimentaryMineral());

List<IMineral> mineralList = list;
mineralList.add(new NonSedimentaryMineral());

for(SedementaryMineral m : list) {
    System.out.println(m); // what happens when it gets to the NonSedimentaryMineral?

You have a serious issue there.

What you can do is this: List<? extends IMineral> mienralList = list

Need Your Help

Download file from S3 to Rails 4 app

ruby-on-rails ruby ruby-on-rails-4 amazon-web-services amazon-s3

I have an AWS VM that runs a daily task and generates several files. I want my Rails app to download these files and place them in a folder within the app. Is there a gem or method in Ruby that can...

Developing with backbone.js, how can I detect when multiple users(browsers) attempt to update?

rest backbone.js

I am very new to backbone.js (and MVC with javascript), and while reading several resources about backbone.js to adopt it in my project, I now have a question: how can I detect when multiple

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.