【问题标题】:How to fix non-static variable this cannot be referenced from a static class with inner classes?如何修复无法从具有内部类的静态类中引用的非静态变量?
【发布时间】:2014-02-23 12:30:20
【问题描述】:

我编写以下代码纯粹是为了好玩,可能仍然存在错误,或者它甚至可能根本不起作用:

public class PrimeGenerator implements PrimitiveIterator.OfInt {
    private final static IntNode HEAD_NODE = new IntNode(2); //error here

    private IntNode lastNode = HEAD_NODE;
    private int current = 0;

    @Override
    public boolean hasNext() {
        return true;
    }
    @Override
    public int nextInt() {
        if (lastNode.value == current) {
            lastNode = lastNode.next;
            return lastNode.value;
        }
        while (true) {
            current++;
            if (isPrime(current)) {
                break;
            }
        }
        appendNode(current);
        return current;
    }

    private boolean isPrime(final int number) {
        PrimeGenerator primeGenerator = new PrimeGenerator();
        int prime = 0;
        while (prime < number) {
            prime = primeGenerator.nextInt();
            if (number % prime == 0) {
                return false;
            }
        }
        return true;
    }

    private void appendNode(final int value) {
        couple(lastNode, new IntNode(value));
    }

    private void couple(final IntNode first, final IntNode second) {
        first.next = second;
        second.previous = first;
    } 

    private class IntNode {
        public final int value;

        public IntNode previous;
        public IntNode next;

        public IntNode(final int value) {
            this.value = value;
        }
    }
}

对于不了解 Java 8 的人,不用担心,PrimitiveIterator.OfIntIterator&lt;Integer&gt; 的工作方式相同。

我遇到的问题在第二行,即:

private final static IntNode HEAD_NODE = new IntNode(2);

我收到警告:non-static variable this cannot be referenced from a static class

我已经搜索过了,它应该可以通过将IntNode 不依赖于PrimeGenerator 来修复,方法是将其移动到自己的公共类中。

但是,如果我不希望 IntNode 被公开,我该怎么办?

【问题讨论】:

  • 将其设为static 类?
  • @OliCharlesworth 这不是捍卫能够实例化它的想法吗?或者它与内部类的工作方式不同,我仍然对此感到困惑。

标签: java class static inner-classes java-8


【解决方案1】:

你应该让你的IntNodestatic

如果你不这样做,这意味着如果没有已经存在的封闭类的实例,IntNode 实例就不能存在。

简而言之,你不能写(前提是IntNode当然是public):

new PrimeGenerator.IntNode(whatever);

但是你必须创建一个新的PrimeGenerator,比如下面的generator,然后写:

generator.new IntNode(whatever);

在这里,您尝试创建一个IntNode 作为PrimeGenerator 的类变量。这不起作用,因为您还没有 PrimeGenerator 的实例。

【讨论】:

  • 是否可以安全地记住静态内部类在其自己的文件中等同于公共类,唯一的区别是内部变体从不对外可见?
  • 不,不完全;我提醒它的方式是静态内部类的实例可以独立于其外部类而存在。如果声明为 public,即使是“实例相关”的内部类也可以从外部看到。
  • 另外请注意,在您的内部类中,您不需要将变量设为public,您可以将它们设为private:它们在内部类中同样可见。
  • 除了 Netbeans 抱怨该变量没有被使用(即使它是由外部类使用的!),我讨厌来自 IDE 的抱怨。
猜你喜欢
  • 2011-09-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
相关资源
最近更新 更多