扩展通用抽象类和正确使用超级
public abstract class AbstractTool<AT extends AbstractThing> {
protected ArrayList<AT> ledger;
public AbstractTool() {
ledger = new ArrayList<AT>();
}
public AT getToolAt(int i) {
return ledger.get(i);
}
// More code Which operates on Ledger ...
}
public class Tool<AT extends AbstractThing> extends AbstractTool {
public Tool() {
super();
}
}
如何正确调用 super 将 Tool
的 AT
泛型传递给 AbstractTool 构造函数?
似乎无论我在声明 Tool
时选择 AT
是什么(例如,Tool
),我总是会得到一个AbstractThing
而不是 Thing
。这似乎违背了泛型的目的……
有帮助吗?
public abstract class AbstractTool<AT extends AbstractThing> {
protected ArrayList<AT> ledger;
public AbstractTool() {
ledger = new ArrayList<AT>();
}
public AT getToolAt(int i) {
return ledger.get(i);
}
// More code Which operates on Ledger ...
}
public class Tool<AT extends AbstractThing> extends AbstractTool {
public Tool() {
super();
}
}
How do I correctly call super to pass the AT
generic of Tool
to the AbstractTool constructor?
It seems no matter what I pick AT
to be when I declare Tool
(Say, Tool<Thing>
), that I always get back an AbstractThing
instead of Thing
. This seems to defeat the purpose of generics...
Help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
换句话说,如果您使用泛型扩展或实现某些内容,请记住为它们定义泛型参数。
In other words, if you extend or implement something with generics, remember to define the generics arguments for them.
难道不应该是
工具扩展 AbstractTool
?Shouldn't it rather be
Tool<AT extends...> extends AbstractTool<AT>
?我认为您可能想要的是:
由于
Tool
是一个具体的类,因此它本身不需要参数化。如果您在声明时初始化List
(哦,记得对接口进行编程),则不需要构造函数,并且因为它是受保护的,所以子类可以直接访问它。I think what you probably want is:
Since
Tool
is a concrete class, it doesn't need to be parametrized itself. There is no need for the constructors if you initialize theList
(oh and remember to program to the interface) at declaration, and because it is protected the subclasses can access it directly.