如何修复非静态变量,这不能从具有内部类的静态类中引用?

时间:2014-02-23 12:30:20

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

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

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<Integer>的工作方式相同。

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

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

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

我已经搜索过,应该可以通过将IntNode取决于PrimeGenerator,将其移到自己的公共类中来修复它。

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

1 个答案:

答案 0 :(得分:3)

您应该制作IntNode课程static

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

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

new PrimeGenerator.IntNode(whatever);

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

generator.new IntNode(whatever);

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

相关问题