我的代碼如下所示:爲什麼Java模板約束將約束類型限制爲返回語句中的擴展類型?
public class Something<T extends Thing> {
private T theThing;
public Something(T aThing) {
theThing = aThing;
}
public T getTheThing() {
return theThing;
}
}
然後,冥冥中,我寫這篇文章:
Something something = new Something<SpecialThing>(new SpecialThing()); // SpecialThing extends Thing
SpecialThing specialThing = something.getTheThing(); // Error: getTheThing() returns object of type Thing instead of SpecialThing!
爲什麼我沒有得到theThing
爲SpecialThing
,但作爲一個Thing
呢?
事情類:
public abstract class Thing {
}
SpecialThing類:
public class SpecialThing extends Thing {
}
提供Thing和SpecialThing類代碼。 – SMA 2014-10-19 13:51:29