Extending Generic Abstract Class & Correct Use of Super

后端 未结 3 1239
生来不讨喜
生来不讨喜 2021-01-11 16:19
public abstract class AbstractTool {
    protected ArrayList ledger;
    public AbstractTool() {
        ledger = new Array         


        
相关标签:
3条回答
  • 2021-01-11 16:41

    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.

    0 讨论(0)
  • 2021-01-11 16:44

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

    0 讨论(0)
  • 2021-01-11 16:49
    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.

    0 讨论(0)
提交回复
热议问题