实例化一个新的内部类时是否需要关键字"this"?

Cod*_*ity 5 java

Oracle Java SE教程的另一个例子.它工作正常,但我不确定在创建内部类的实例时是否/为什么'这'是必要的.无论我是否把它取出,结果似乎都是一样的.

要清楚,我指的是:InnerEvenIterator iterator = this.new InnerEvenIterator(); //不确定为什么要使用'this'

public class DataStructure {
    // create an array

    private final static int SIZE = 15;
    private int[] arrayOfInts = new int[SIZE];

    public DataStructure() {
        // fill the array with ascending integer values
        for (int i = 0; i < SIZE; i++) {
            arrayOfInts[i] = i;
        }
    }

    public void printEven() {
        // prints out the value of even indices in the array
        InnerEvenIterator iterator = this.new InnerEvenIterator(); // not sure why using 'this'
        while (iterator.hasNext()) {
            System.out.println(iterator.getNext() + " ");
        }
    }

    // inner class implements the Iterator pattern
    private class InnerEvenIterator {
        // start stepping through the array from the beginning

        private int next = 0;

        public boolean hasNext() {
            // check if a current element is the last in the array
            return (next <= SIZE - 1); // -1 b/c dealing with array's length.
        }

        public int getNext() {
            // record a value of an even index of the array
            int retValue = arrayOfInts[next];
            // get the next even element
            next += 2;
            return retValue;
        }
    }

    public static void main(String s[]) {
        // fill the array with integer values and print out only
        // values of even indices
        DataStructure ds = new DataStructure();
        ds.printEven();
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ung 10

this.在这种情况下,您不需要a .但是,必须始终使用封闭实例构造内部类,因此this.只需向读者说明这一点.

如果你不在非静态方法中DataStructure(即,如果this不存在,或者不是实例DataStructure),那么你必须实际指定DataStructure创建时的实例InnerEvenIterator:

InnerEvenIterator iterator = dataStructure.new InnerEvenIterator();
Run Code Online (Sandbox Code Playgroud)