-1

Let's say I have these four classes:

public interface A {}

public interface B {
    public A getA();
}

public class C implements A {}

public class D implements B {
    public C getA() {
        return new C();
    }
}

This compiles well. However if I have this code I get a compilation error:

public interface A {}

public interface B {
    public List<A> getA();
}

public class C implements A {}

public class D implements B {
    public List<C> getA() {
        return new ArrayList<C>();
    }
}

public class E implements B {
    public List<A> getA() {
        return new ArrayList<C>();
    }
}

What is the reason that allows to return a C in the method getA, in the first example, but generates an error in the second example when I return a List?

It looks to me that both examples should compile or throw an error.

Thanks.

EDIT I read the post using Dog/Animal, however my doubt is different. I have added the class E. If you call getA in class E you get a List as defined in the interface. Then why it fails compiling for class E?

daniel sp
  • 937
  • 1
  • 11
  • 29
  • 3
    possible duplicate of [Is List a subclass of List? Why aren't Java's generics implicitly polymorphic?](http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p) – Tunaki Sep 30 '15 at 09:37
  • Hi Tunaki. Please see my edit. – daniel sp Sep 30 '15 at 09:53

1 Answers1

3

This is relate to java generics. You have defined the return type of method in interface as List<A> but you are trying to return a List<C> from the actual implementation. If you actually wanna return a List<C> from the method then you have to change your interface method as follows

public List<? extends A> getA();

Explanation why can't return new ArrayList<C>();

Let say it is valid to return as u mentioned. Then

List<A> listA = getA(); // This will compile if allowed
listA.add(new A()); // this will also valid since reference type is A. 

So you can see that it is no point of allowing the way you mentioned