rockwe
rockwe

Reputation: 11

Why inner class instance variable can't mofidy the outer class instance variable,but the inner class local variable can

Why the test variable occurs compile error which inside the localClassMethod and outside the tt method,but compile is ok in tt method. It means inner class instance variable can't mofidy the outer class instance variable,but the inner class local variable can modify the outer class instance variable.

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
            }
        }
    }
}

Upvotes: 0

Views: 36

Answers (1)

Andreas
Andreas

Reputation: 159155

Although the lines look similar, they are not the same:

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.
            }
        }
    }
}

If you want to run code to assign value 1 to field test when a new instance of localClassInMethod is created, use an instance initializer block:

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

            public void tt() {
                ...
            }
        }

That is the same as putting the statement in every constructor:

        class localClassInMethod {
            int k = test;

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

            public void tt() {
                ...
            }
        }

Upvotes: 2

Related Questions