簡體   English   中英

為什么內部類實例變量不能修改外部類實例變量,而內部類局部變量可以

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

為什么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
            }
        }
    }
}

雖然線條看起來相似,但它們並不相同:

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

如果要在創建localClassInMethod的新實例時運行代碼以將值1分配給字段test ,請使用實例初始值設定項塊:

        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() {
                ...
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM