java bounded wildcards understanding issue -
this question has answer here:
i new java , read many articles on net ? super t or ? extends t still don't it. here example:
public class a<t> { private t t; public t gett() { return t; } public void sett(t t) { this.t = t; } public void doextends(a<? extends t> b) { t t = b.gett(); //ok this.sett(b.gett()); // ok b.sett(this.gett()); // error } public void dosuper(a<? super t> b) { t t = b.gett(); // error this.sett(b.gett()); // error b.sett(this.gett()); // ok } } why there errors? question different 1 referenced in comments
the thing follows:
in doextends(a<? extends t> b) specify b of type a encapsulating may unknown subclass of t. such fine t t = b.gett() since b.gett() produces extends t (so can cast t). same holds true this.sett(b.gett()) - equivalent this.sett(t). let's @ method's last line b.sett(...). said before a contains unknown subclass of t. want stuff in t (this.gett() produces t) , cannot sure t matches subclass may inside b - that's why doesn't work.
next on dosuper(a<? super t> b) - here b contains unknown superclass of t or maybe t itself. that's why last line - setting value - fine. this.gett() produces t can cast of superclasses. when value b.gett() known it's unknown superclass of t not guaranteed t. don't know class be.
Comments
Post a Comment