Extending Generic Abstract Class & Correct Use of Super

99封情书 提交于 2019-12-04 00:21:07

问题


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?


回答1:


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.




回答2:


Shouldn't it rather be Tool<AT extends...> extends AbstractTool<AT>?




回答3:


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 Tool is 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.



来源:https://stackoverflow.com/questions/1417930/extending-generic-abstract-class-correct-use-of-super

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!