【发布时间】:2017-11-30 11:10:05
【问题描述】:
如果我有这样的抽象类:
public abstract class Item
{
private Integer value;
public Item()
{
value=new Integer(0);
}
public Item(Integer value)
{
this.value=new Integer();
}
}
还有一些从 Item 派生的类,如下所示:
public class Pencil extends Item
{
public Pencil()
{
super();
}
public Pencil(Integer value)
{
super(value);
}
}
我不明白为什么我不能使用泛型调用构造函数:
public class Box <T extends Item>
{
T item;
public Box()
{
item=new T(); // here I get the error
}
}
我知道可能有一个没有构造函数的类型,但这种情况是不可能的,因为 Pencil 的构造函数没有参数,而 Item 是抽象的。
但是我从 eclipse 中得到这个错误:
无法实例化类型 T
我不明白为什么,以及如何避免这种情况?
【问题讨论】:
-
考虑当你有另一个类扩展
Item的情况,除了这个类只有一个坚持至少一个参数的构造函数。 -
对于所有需要类似东西的人,我认为最简单的解决方案是制作以下内容:stackoverflow.com/questions/1090458/…