在范围

时间:2017-12-01 20:40:09

标签: java class inner-classes

我还在学习并且正在尝试使用嵌套的STATIC类实现DoublyLinkedLists并得到以下错误:

No enclosing instance of the type OuterClass.StaticNestedClass is accessible in scope 实际错误:
No enclosing instance of the type SolutionDLL.Node is accessible in scope

我在外部类SolutionDLL类中有两个 STATIC 嵌套类:

class SolutionDLL {
    public static class Node {
        private Object element;
        private Node   next;
        private Node   previous;

        Node(Object elementIn, Node nextNodeIn, Node prevNodeIn) {
            element = elementIn;
            next    = nextNodeIn;
            previous = prevNodeIn;
        }

        public Object getElement() {
            return element;
        }

        public Node getNext() {
            return next;
        }

        public Node getPrevious() {
            return previous;
        }

    }

    public static class DLList {
        public void addFirst(Node n) {
            SolutionDLL.Node tempNode = new SolutionDLL.Node(
                SolutionDLL.Node.this.getElement(),
                SolutionDLL.Node.this.getNext(), 
                SolutionDLL.Node.this.getPrevious()); 
            // do something
        }
    }
}

无论我这样打电话:
SolutionDLL.Node.this.getElement()
像这样:
Node.this.getElement()

我仍然得到错误。我给出了骨架代码,这是我第一次使用嵌套类实现。所以任何帮助都将得到很好的赞赏。 谢谢!

1 个答案:

答案 0 :(得分:0)

SolutionDLL.Node,就像任何一个类一样,没有this字段。 this字段仅在对象及其对象类的内部类中可用。

更改addFirst以获取值{fomr n节点:

public static class DLList {
   private Node firstNode = null;

    public void addFirst(Node n) {

        //do something with the first node before it is assigned to the n
        if (firstNode != null){
            SolutionDLL.Node tempNode = new SolutionDLL.Node(
            firstNode.getElement(),
            firstNode.getNext(), 
            firstNode.getPrevious()); 
         }
         firstNode = n;
        // do something
    }
}