4

ネストされたクラスに関する Oracle ドキュメントを読んでいるときに、出力が理解できないこのコードを見つけました。誰かがこれを説明してもらえますか?

public class ShadowTest {

    public int x = 0;

    class FirstLevel {

        public int x = 1;

        void methodInFirstLevel(int x) {
            System.out.println("x = " + x);
            System.out.println("this.x = " + this.x);
            System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
        }
    }

    public static void main(String... args) {
        ShadowTest st = new ShadowTest();
        ShadowTest.FirstLevel fl = st.new FirstLevel();
        fl.methodInFirstLevel(23);
    }
}

この例の出力は次のとおりです。

x = 23
this.x = 1
ShadowTest.this.x = 0 //why is 0 printed here? why not 1 because "this" is the object of FirstLevel class.

元のコードはここにあります

4

2 に答える 2

6

ローカル変数はと をx隠します。this.xShadowTest.this.x

内部クラスのインスタンス変数 ( this.x) は、外側のクラス ( からアクセスできる) のインスタンス変数を隠しますShadowTest.this.x

System.out.println("x = " + x); // prints the local variable passed to the method
System.out.println("this.x = " + this.x); // prints the instance variable of the inner class
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x); // prints the instance variable of the enclosing class instance
于 2015-11-11T08:53:38.193 に答える