Declaring static generic variables in a generic class

前端 未结 4 634
难免孤独
难免孤独 2021-02-13 13:43

I\'ve read that you cannot declare static variables/methods inside a generic class and I really have no idea how to solve my problem or work around it so I ask for your guidance

4条回答
  •  庸人自扰
    2021-02-13 14:09

    Try this approach: Define a protected abstract method that subclasses implement to return a static object for their class.

    There may be some logic issues etc, but the basics of the answer are here (ie this compiles):

    EDITED: Now delegating to HeadAndTail

    /**  A subclass of Nexus */
    abstract class Nexus> { // This syntax lets you confine T to a subclass of Nexus
        private T next;
    
        protected Nexus() {
            this.add((T) this);
        }
    
        public T add(T obj) {
            // Delegate to HeadAndTail
            return getHeadAndTail().add(obj);
        }
    
        /** @return a static for the class */
        protected abstract HeadAndTail getHeadAndTail();
    }
    
    /** Bundled into one Object for simplicity of API */
    class HeadAndTail> {
        T head = null;
        T tail = null;
        int num = 0;
    
        public T add(T obj) {
            obj.next = null;
            if (num++ == 0)
                head = tail = obj;
            else
                tail = tail.next = obj;
    
            return obj;
        }
    }
    
    class ConcreteNexus extends Nexus {
        // This is the static object all instances will return from the method
        private static HeadAndTail headAndTail = new HeadAndTail();
    
        protected HeadAndTail getHeadAndTail() {
            return headAndTail; // return the static
        }
    }
    

提交回复
热议问题