2014-10-19 77 views
2

我的代码如下所示:为什么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! 

为什么我没有得到theThingSpecialThing,但作为一个Thing呢?

事情类:

public abstract class Thing { 
} 

SpecialThing类:

public class SpecialThing extends Thing { 
} 
+1

提供Thing和SpecialThing类代码。 – SMA 2014-10-19 13:51:29

回答

4

的原因是,您使用的是原始类型引用您的Something。这意味着Java唯一可以肯定地说的是,返回的类型扩展为Thing,所以这就是你所得到的类型。

添加类型参数像这样返回SpecialThing

Something<SpecialThing> something = new Something<SpecialThing>(new SpecialThing()); 
SpecialThing specialThing = something.getTheThing(); 
3

因为你没有指定变量声明的类型。你可能用SpecialThing实例化了它,但那不是你记得它的方式。

你会注意到它在你使用它的时候会起作用。

Something<SpecialThing> something = new Something<SpecialThing>(new SpecialThing()); 

与定义ArrayList t = new ArrayList<String>();相同。这仍将被视为ArrayList<Object>,而不是ArrayList<String>

JavaDocs on raw types