java - Class that implements an interface with a method returning List of interfaces generates compilation error -
let's have these 4 classes:
public interface {} public interface b { public geta(); } public class c implements {} public class d implements b { public c geta() { return new c(); } }
this compiles well. if have code compilation error:
public interface {} public interface b { public list<a> geta(); } public class c implements {} 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 reason allows return c in method geta, in first example, generates error in second example when return list?
it looks me both examples should compile or throw error.
thanks.
edit read post using dog/animal, doubt different. have added class e. if call geta in class e list defined in interface. why fails compiling class e?
this relate java generics. have defined return type of method in interface list<a>
trying return list<c>
actual implementation. if wanna return list<c>
method have change interface method follows
public list<? extends a> geta();
explanation why can't return new arraylist<c>();
let valid return u mentioned. then
list<a> lista = geta(); // compile if allowed lista.add(new a()); // valid since reference type a.
so can see no point of allowing way mentioned
Comments
Post a Comment