Search code examples
javaocpjp

Why List<SuperClassType> newList = new ArrayList<SubClassType>() violates type safety?


Possible Duplicate:
Is `List<Dog>` a subclass of `List<Animal>`? Why aren’t Java’s generics implicitly polymorphic?

I have declared these classes:

class Cereal{}

And:

public class Flakes extends Cereal{
    public static void main(String[] args) {
       List<Cereal> newList = new ArrayList<Flakes>();
    }
}

But when I try to compile these Java source code, this compilation error appears:

Type mismatch: cannot convert from ArrayList<Flakes> to List<Cereal>

My question is: Why is not possible that conversion? Is it violating the type safety rule? Or?

Thanks in advance for your responses.


Solution

  • Because types are rigid unless defined. You want to try below:

         List<? extends Cereal> newList = new ArrayList<Flakes>();
    

    This means that its list objects extending Cereal and thus above statement becomes valid.