我正在为SCJP做准备,而在阅读有关嵌套类型时感到困惑。有一个简单的问题,我无法理解结果。

public class Outer {
    private int innerCounter;

    class Inner {
        Inner() {
            innerCounter++;
        }

        public String toString() {
            return String.valueOf(innerCounter);
        }
    }

    private void multiply() {
        Inner inner = new Inner();
        this.new Inner();
        System.out.print(inner);
        inner = new Outer().new Inner();
        System.out.println(inner);
    }

    public static void main(String[] args) {
        new Outer().multiply();
    }
}


它打印

21


知道计数器不是静态的,那么前两个对象如何被视为一个对象?

最佳答案

非静态内部类可以访问其外部类的所有成员。就像它真的定义为:

class Outer {

    private int innerCount;

    class Inner() {
        private final Outer owner;

        public Inner(Outer owner) {
            this.owner = owner;
            this.owner.innerCount++;
        }
    }

    private void multiply() {
        Inner inner = new Inner(this);
        ...
    }
}


因此,让我注释您的方法:

private void multiply() {
    // this.innerCount = 0

    Inner inner = new Inner();
    // this.innerCount = 1

    this.new Inner();
    // this.innerCount = 2

    System.out.print(inner);  // Prints "2"

    // Creates a new Outer (with a separate innerCount)
    // then uses that to create a new Inner, which updates
    // the new innerCount
    inner = new Outer().new Inner();
    // inner.innerCount = 1

    System.out.println(inner);  // Prints "1"
}

10-06 03:03