java 扩展通用抽象类和正确使用 Super
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1417930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extending Generic Abstract Class & Correct Use of Super
提问by iny
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 ATgeneric of Toolto the AbstractTool constructor?
如何正确调用 super 将AT泛型传递Tool给 AbstractTool 构造函数?
It seems no matter what I pick ATto be when I declare Tool(Say, Tool<Thing>), that I always get back an AbstractThinginstead of Thing. This seems to defeat the purpose of generics...
似乎无论我AT在声明Tool(Say, Tool<Thing>)时选择什么,我总是返回一个AbstractThing而不是Thing. 这似乎违背了泛型的目的......
Help?
帮助?
回答by iny
public class Tool<AT extends AbstractThing> extends AbstractTool<AT> {
In other words, if you extend or implement something with generics, remember to define the generics arguments for them.
换句话说,如果您使用泛型扩展或实现某些东西,请记住为它们定义泛型参数。
回答by Volker Stolz
Shouldn't it rather be
Tool<AT extends...> extends AbstractTool<AT>?
不应该是
Tool<AT extends...> extends AbstractTool<AT>吗?
回答by Robert
I think what you probably want is:
我想你可能想要的是:
public abstract class AbstractTool<AT extends AbstractThing> {
protected List<AT> ledger = new ArrayList<AT>();
public AT getToolAt(int i) {
return ledger.get(i);
}
// More code Which operates on Ledger ...
}
public class Tool extends AbstractTool<Thing> {
// Tool stuff ...
}
Since Toolis a concrete class, it doesn't need to be parametrized itself. There is no need for the constructors if you initialize the List(oh and remember to program to the interface) at declaration, and because it is protected the subclasses can access it directly.
由于Tool是一个具体的类,因此不需要对其本身进行参数化。如果List在声明时初始化(哦,记得对接口编程),则不需要构造函数,并且因为它是受保护的,子类可以直接访问它。

