【问题标题】:No enclosing instance of the type OuterClass.StaticNestedClass is accessible in scope范围内无法访问 OuterClass.StaticNestedClass 类型的封闭实例
【发布时间】:2017-12-01 20:40:09
【问题描述】:

我仍在学习,目前正在尝试使用嵌套的 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()

我仍然得到错误。我已经给出了框架代码,这是我第一次使用嵌套类实现。因此,我们将不胜感激任何帮助。 谢谢!

【问题讨论】:

  • 您使用的语法仅适用于内部类。这里没有内部类。

标签: java class inner-classes


【解决方案1】:

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

更改 addFirst 以获取来自 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
    }
}

【讨论】:

  • 但问题是我想用方法中传递的节点替换原来的FirstNode,这就是我尝试这样做的原因。那么如何访问原始节点?在用方法中的n 替换之前,我需要以某种方式访问​​之前的 firstNode。
  • 该方法是在 DLList 而不是 Node 本身上调用的。您没有保留对第一个节点的引用。您必须将其视为对象而不是类。查看我更新的代码,希望能回答您的问题。
  • 哦,好吧,我明白了,我会尝试这样做。谢谢! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-02
  • 2011-12-15
  • 2016-11-20
  • 2013-04-11
  • 2012-06-17
  • 1970-01-01
相关资源
最近更新 更多