Cannot reference this before supertype constructor has been called

前端 未结 4 1463
萌比男神i
萌比男神i 2021-01-16 16:17

I\'m attempting to implement a circular queue class in Java. And in doing so I had to created a node class to group together elements and pointers to the next node. Being ci

相关标签:
4条回答
  • 2021-01-16 16:46

    You cannot refer tho this (or super) in a constructor, so you should change your code like this:

    public class Node<Key>{
        private Key key;
        private Node<Key> next;
        public Node(){
        key = null;
            next = this;
        }
        public Node(final Key k){
        key = null;
            next = this;
        }
        public Node(final Key k, final Node<Key> node){
            key = k;
            next = node;
        }
        public boolean isEmpty(){return key == null;}
        public Key getKey(){return key;}
        public void setKey(final Key k){key = k;}
        public Node<Key> getNext(){return next;}
        public void setNext(final Node<Key> n){next = n;}
    }
    
    0 讨论(0)
  • 2021-01-16 16:52

    Can not pass "this" as a parameter to call the constructor.

    0 讨论(0)
  • 2021-01-16 16:54

    The compile error is

    Cannot refer to 'this' nor 'super' while explicitly invoking a constructor
    

    Basically, you cannot use "this" from inside "this(...)"

    0 讨论(0)
  • 2021-01-16 16:54

    You dont need to pass it in all cases. since you can refer to it in the other construtor

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