为什么内部类实例变量不能修改外部类实例变量,但是内部类局部变量可以

时间:2019-12-14 07:47:25

标签: java anonymous-inner-class

为什么test变量发生在localClassMethod内部和tt方法外部的编译错误,但是在tt方法中可以编译。 这意味着内部类实例变量不能修改外部类实例变量,但是内部类局部变量可以修改外部类实例变量。

public class Outer {
    int test = 0;

    void classMethod() {
        class localClassInMethod {
            int k = test;//compile ok
            test = 1;//compile error

            public void tt() {
                test++;//compile ok
                int m = test;//compile ok
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

尽管这些行看起来很相似,但它们并不相同:

public class Outer {
    int test = 0; // This is a field declaration, with initializer.

    void classMethod() {
        class localClassInMethod {
            int k = test; // This is a field declaration, with initializer.
            test = 1;     // This is an assignment statement, and those are only
                          // valid inside a method body or initializer block.

            public void tt() {
                test++;       // This is a post-increment expression statement.
                int m = test; // This is a local variable declaration, with initializer.

                test = 2;     // Assignment statement is valid here.
            }
        }
    }
}

如果要运行代码以在创建1的新实例时将值test分配给字段localClassInMethod,请使用实例初始化程序块:

        class localClassInMethod {
            int k = test;
            { // Initializer block.
                test = 1; // Assignment statement is valid here.
            }

            public void tt() {
                ...
            }
        }

这与将语句放入每个构造函数相同:

        class localClassInMethod {
            int k = test;

            public localClassInMethod() {
                test = 1; // Assignment statement is valid here.
            }

            public void tt() {
                ...
            }
        }