0

I've got the next

public interface MyInterface{}
public class ClassA implements MyInterface(){}
public class ClassB extends ClassA{}

In theory, the valid references types for an object B are the following:

MyInterface myIn = new ClassB();
ClassA o1 = new ClassB();
ClassB o2 = new ClassB(); 
Object o3 = new ClassB(); 

If I try to do something like this ... List<MyInterface> o1 = new ArrayList<ClassB>();

I get a compilance error. Any idea?

VNT
  • 934
  • 2
  • 8
  • 19
silvia Dominguez
  • 445
  • 1
  • 4
  • 16
  • `Generics` are working at compile time, so the `generic` `` in `ArrayList()` is quite unecessary. The `generic` you´ll see as more importent is `List`, as this defines the `generic` `List` at compile time. As a sidenode, that´s also why jdk 1.7 introduced the empty `diamond operator` when intializing a `List` for example, the right hand `generic` simple can be left out. – SomeJavaGuy May 29 '17 at 10:45
  • 1
    Possible duplicate of [Is List a subclass of List? Why aren't Java's generics implicitly polymorphic?](https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p) – Jorn Vernee May 29 '17 at 10:47

1 Answers1

0

An ArrayList<ClassB> can contain only instances of ClassB or sub-classes of ClassB.

On the other hand, a List<MyInterface> can also contain instances of ClassA (which are not necessarily instances of ClassB) and any other instances that implement MyInterface.

Therefore you can't assign an ArrayList<ClassB> to a List<MyInterface> variable.

If you want the o1 list to contain any MyInterface instances, you should assign to it an ArrayList<MyInterface>.

If you want o1 to contain only instances of ClassB, change its type to List<ClassB>.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • But in theory all objects of class ClassB are objects of ClassA and therefore of implemented interface too. Indeed if I try to do this Myinterface o1 = new ClassB(); it compiles ok – silvia Dominguez May 29 '17 at 10:49
  • 1
    @silviaDominguez But not all objects of ClassA have to be objects of ClassB. – Eran May 29 '17 at 10:50
  • 1
    @silviaDominguez `ClassB` implements `MyInterface`, so you can make that assignment. However, `ArrayList` does not implement `List` - it implements `List`. And `List` is not a sub-interface of `List` and cannot be assigned to a variable of this type. – Eran May 29 '17 at 10:55
  • @EranThus although ArrayList implements List, here I can´t use polymorphism right? – silvia Dominguez May 29 '17 at 11:10